如何在 Python 中使用 lambda 进行排序 [英] How to sort with lambda in Python
本文介绍了如何在 Python 中使用 lambda 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 中,我尝试使用 lambda 按日期排序.我无法理解我的错误信息.消息是:
In Python, I am trying to sort by date with lambda. I can't understand my error message. The message is:
<lambda>() takes exactly 1 argument (2 given)
我的线路是
a = sorted(a, lambda x: x.modified, reverse=True)
推荐答案
使用
a = sorted(a, key=lambda x: x.modified, reverse=True)
# ^^^^
在 Python 2.x 上,sorted
函数按以下顺序接受其参数:
On Python 2.x, the sorted
function takes its arguments in this order:
sorted(iterable, cmp=None, key=None, reverse=False)
因此如果没有 key=
,您传入的函数将被视为一个 cmp
函数,它带有 2 个参数.
so without the key=
, the function you pass in will be considered a cmp
function which takes 2 arguments.
这篇关于如何在 Python 中使用 lambda 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文