python sort tuple by different criteria

好久不见. 提交于 2019-12-20 07:47:48

问题


I have a list a = [(1,'a'), (1,'b'), (2,'c')], and I want to get this list: [(2,'c'), (1,'a'), (1,'b')]

If I do this:

sorted(a, reverse=True)

I can only get:

[(2,'c'), (1,'b'), (1,'a')]

How can I get the list I want?


回答1:


If you want to preserve the sort order in the original list, but sort only by the first element, you can do

>>> from operator import itemgetter
>>> a = [(1,'a'), (1, 'x'), (1,'b'), (2,'c')]
>>> sorted(a, key=itemgetter(0), reverse=True)
[(2, 'c'), (1, 'a'), (1, 'x'), (1, 'b')]

In Python the sort and sorted functions use the TimSort algorithm, which is a stable sort. Being stable means that the original relative ordering is preserved for those elements that compare equal to each other.

If you want to sort by multiple criteria at the same time, you can use a function for the key in case of integers, returning the opposite number of the number for reversing, but in general case you could do so by sorting several times, in reverse order:

>>> b = sorted(a, key=itemgetter(1))        # sort by second element, ascending
>>> b.sort(key=itemgetter(0), reverse=True) # sort by first element, descending
>>> b
[(2, 'c'), (1, 'a'), (1, 'b'), (1, 'x')]



回答2:


You may achieve this by using lambda function with sorted:

>>> sorted(a, key=lambda x: (-x[0], x[1]))
[(2, 'c'), (1, 'a'), (1, 'b')]

This will sort the list in descending order of the value at index 0, and then ascending order of value at index 1




回答3:


Try this,

from operator import itemgetter
sorted(a, key=itemgetter(0),reverse=True)

Result

[(2, 'c'), (1, 'a'), (1, 'b')]


来源:https://stackoverflow.com/questions/39093546/python-sort-tuple-by-different-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!