gpt4 book ai didi

python - lambda 如何选择要返回的值

转载 作者:太空宇宙 更新时间:2023-11-04 03:30:27 24 4
gpt4 key购买 nike

在一个教程中,我看到一段我验证有效的代码: 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).

关于python - lambda 如何选择要返回的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31269428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com