英文:
Can you get enter two functions or values in Lambda function
问题
Lambda函数可以用来替代get_name()
函数的功能,下面是Lambda表达式的示例,等同于get_name()
函数的功能:
lambda student: (student['Names'], student['House'])
你可以在sorted()
函数中使用这个Lambda表达式来排序学生信息,就像这样:
sorted_students = sorted(students, key=lambda student: (student['Names'], student['House']))
for student in sorted_students:
print(f"{student['Names']} is in {student['House']}")
这将根据姓名('Names')首先排序学生,然后按照房屋('House')进行次要排序。
英文:
Sorry if the question is confusing or stupid but basically in a sorted function I want Lambda to check the names and if they both have the same name check to see which house comes for example
def get_name(list):
return list['Names'], list['House']
would check the name then the house they're in can lambda do the same or just take one parameter
for student in sorted(students, key=lambda studen: studen['Names']):
print(f"{student['Names']} is in {student['House']}")
My question is: how to write Lambda that equals to the get_name()
function?
答案1
得分: 2
只返回翻译好的部分:
只需让您的 lambda 返回一个元组:
sorted(students, key=lambda student: (student['Names'], student['House']))
---
或者,可以使用您定义的 `get_name` 函数:
sorted(students, key=get_name)
<details>
<summary>英文:</summary>
Simply have your lambda return a tuple:
sorted(students, key=lambda student: (student['Names'], student['House']))
---
Or alternatively, using the `get_name` function that you defined:
sorted(students, key=get_name)
</details>
# 答案2
**得分**: -1
以下是翻译好的代码部分:
```python
students = [
{'Names': 'Alice', 'House': 'Gryffindor'},
{'Names': 'Bob', 'House': 'Hufflepuff'},
{'Names': 'Alice', 'House': 'Ravenclaw'},
{'Names': 'Charlie', 'House': 'Slytherin'},
{'Names': 'Eve', 'House': 'Gryffindor'}
]
for student in sorted(students, key=lambda student: (student['Names'], student['House'])):
print(f"{student['Names']} is in {student['House']}")
上面的代码使用作为key
参数的lambda函数返回每个学生的元组(student['Names'], student['House'])
。当sorted函数比较两个学生时,首先比较他们的名字,如果名字相同,则比较他们的所属学院。这样可以实现所需的排序行为,即具有相同名字的学生按照他们所在的学院排序。
英文:
students = [
{'Names': 'Alice', 'House': 'Gryffindor'},
{'Names': 'Bob', 'House': 'Hufflepuff'},
{'Names': 'Alice', 'House': 'Ravenclaw'},
{'Names': 'Charlie', 'House': 'Slytherin'},
{'Names': 'Eve', 'House': 'Gryffindor'}
]
for student in sorted(students, key=lambda student: (student['Names'], student['House'])):
print(f"{student['Names']} is in {student['House']}")
Try the code above.
The lambda function used as the key
parameter returns a tuple (student['Names'], student['House'])
for each student. When the sorted function compares two students, it will first compare their names, and if the names are the same, it will then compare their houses. This achieves the desired sorting behavior where students with the same name are sorted by their houses.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论