问题描述
我不清楚以下内容如何工作:
It is unclear to me how the following works:
In [1]: student_tuples = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
In [2]: sorted(student_tuples, key=lambda student: student[2])
Out [2]: [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] # sort by age
但是
In [3]: st = lambda student: student[2]
In [4]: st(student_tuples)
Out [4]: ('dave', 'B', 10)
为什么前一个示例中的[2]
引用单个元组的索引,而在lambda函数中,它返回列表中的第二个元组?
Why does the [2]
in the former sample refer to the index for the individual tuples, when in a lambda function it returns the 2nd tuple in the list?
推荐答案
由于排序时,将对要排序的列表中的每个元素调用一次key函数.这就是为什么它不是lambda student:
而不是lambda student_tuples:
的原因(不是参数的命名有任何改变,只是在解释命名选择).
Because when you're sorting, the key function is called once for every element of the list being sorted. That's why it's lambda student:
not lambda student_tuples:
(not that the naming of parameters changes anything, just explaining the naming choice).
您可以通过打印键函数的参数直接看到此信息:
You can see this directly by printing the argument of the key function:
student_tuples = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
def my_key(student):
print(student)
return student[2]
sorted(student_tuples, key=my_key)
# calls to my_key print:
# ('john', 'A', 15)
# ('jane', 'B', 12)
# ('dave', 'B', 10)
my_key(student_tuples)
# prints (not returns):
# [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
这篇关于python-使用键功能对序列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!