python - 使用键函数对序列进行排序

时间:2018-05-07 22:14:34

标签: python list lambda key

我不清楚以下是如何工作的:

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函数中它返回列表中的第二个元组时?

1 个答案:

答案 0 :(得分:4)

因为当您进行排序时,对于要排序的列表的每个元素,都会调用一次键函数。这就是为什么lambda student:不是lambda student_tuples:(不是参数的命名会改变任何东西,只是解释命名选择)。

您可以通过打印关键功能的参数直接看到这一点:

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)]