在一个教程中,我看到一段我验证有效的代码: https://wiki.python.org/moin/HowTo/Sorting
>>> student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
为什么 python 知道 student[2] 指的是每个元组的第三个元素?为什么它不尝试按第三个元组排序,而不是每个元组的第三项?
请您参考如下方法:
因为 sorted 函数将其可迭代参数的元素发送到 lambda 函数。在这种情况下,元组将被发送到 lambda。
key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
