How to sort with lambda in Python

2019-01-30 09:26发布

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)

The line I have is

a = sorted(a, lambda x: x.modified, reverse=True)

标签: python lambda
1条回答
可以哭但决不认输i
2楼-- · 2019-01-30 10:14

Use

a = sorted(a, key=lambda x: x.modified, reverse=True)
#             ^^^^

On Python 2.x, the sorted function takes its arguments in this order:

sorted(iterable, cmp=None, key=None, reverse=False)

so without the key=, the function you pass in will be considered a cmp function which takes 2 arguments.

查看更多
登录 后发表回答