按第二个值,reverse = True,然后按键,reverse = False,对元组列表进行排序 [英] Sort a list of tuples by second value, reverse=True and then by key, reverse=False
问题描述
我需要首先对字典进行排序,将值与reverse=True
进行排序,对于重复值,需要对键进行排序,reverse=False
到目前为止,我有这个
dict = [('B', 3), ('A', 2), ('A', 1), ('I', 1), ('J', 1)]
sorted(dict.items(), key=lambda x: (x[1],x[1]), reverse=True)
返回...
[('B', 3), ('A', 2), ('J', 1), ('I', 1), ('A', 1)]
但我需要这样:
[('B', 3), ('A', 2), ('A', 1), ('I', 1), ('J', 1)]
如您所见,
当值相等时,我只能按照指定的降序对键进行排序...但是如何使它们以升序的方式进行排序?
以下内容适用于您的输入:
d = [('B', 3), ('A', 2), ('A', 1), ('I', 1), ('J', 1)]
sorted(d,key=lambda x:(-x[1],x[0]))
由于值"是数字,因此您可以通过更改符号来轻松地反转排序顺序.
换句话说,这种排序按值(-x[1]
)进行排序(负号先放置大数字),然后对相同的数字按键(x[0]
)进行排序. /p>
如果不能轻易地否定"您的值以将大项目放在首位,那么一个简单的解决方法是将两次排序:
from operator import itemgetter
d.sort(key=itemgetter(0))
d.sort(key=itemgetter(1),reverse=True)
之所以有效,是因为python的排序是稳定的.
I need to sort a dictionary by first, values with reverse=True
, and for repeating values, sort by keys, reverse=False
So far, I have this
dict = [('B', 3), ('A', 2), ('A', 1), ('I', 1), ('J', 1)]
sorted(dict.items(), key=lambda x: (x[1],x[1]), reverse=True)
which returns...
[('B', 3), ('A', 2), ('J', 1), ('I', 1), ('A', 1)]
but I need it to be:
[('B', 3), ('A', 2), ('A', 1), ('I', 1), ('J', 1)]
as you can see, when values are equal, I can only sort the key in a decreasing fashion as specified... But how can I get them to sort in an increasing fashion?
The following works with your input:
d = [('B', 3), ('A', 2), ('A', 1), ('I', 1), ('J', 1)]
sorted(d,key=lambda x:(-x[1],x[0]))
Since your "values" are numeric, you can easily reverse the sort order by changing the sign.
In other words, this sort puts things in order by value (-x[1]
) (the negative sign puts big numbers first) and then for numbers which are the same, it orders according to key (x[0]
).
If your values can't so easily be "negated" to put big items first, an easy work-around is to sort twice:
from operator import itemgetter
d.sort(key=itemgetter(0))
d.sort(key=itemgetter(1),reverse=True)
which works because python's sorting is stable.
这篇关于按第二个值,reverse = True,然后按键,reverse = False,对元组列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!