如何在Python中使用Lambda进行排序 [英] How to sort with lambda in Python

查看:207
本文介绍了如何在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函数.

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

这篇关于如何在Python中使用Lambda进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆