lambda如何选择要返回的值

2024-04-20 09:32:32 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个教程中,我看到了一段我验证过的代码: 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]引用每个元组的第三个元素?为什么不尝试按第三个元组排序,而不是按每个元组的第三项排序?你知道吗


Tags: 代码httpsorg排序wiki教程johnstudent
1条回答
网友
1楼 · 发布于 2024-04-20 09:32:32

因为sorted函数将其iterable参数的元素发送给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).

相关问题 更多 >