本文介绍了按任意Lambda排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何通过任意函数描述的键对列表进行排序?例如,如果我有:
How can I sort a list by a key described by an arbitrary function? For example, if I have:
mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
我想按每个成员的第二个元素对"mylist"进行排序,例如
I'd like to sort "mylist" by the second element of each member, e.g.
sort(mylist, key=lambda x: x[1])
我该怎么做?
推荐答案
您基本上已经拥有它:
>>> mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
>>> mylist.sort(key=lambda x: x[1])
>>> print mylist
给予:
[['bar', 0, 'b'], ['quux', 1, 'a']]
这将对mylist进行排序.
That will sort mylist in place.
[由于@Daniel的更正,此段进行了编辑.] sorted
将返回已排序的新列表,而不是实际更改输入,如 http://wiki.python.org/moin/HowTo/Sorting/.
[this para edited thanks to @Daniel's correction.] sorted
will return a new list that is sorted rather than actually changing the input, as described in http://wiki.python.org/moin/HowTo/Sorting/.
这篇关于按任意Lambda排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!