How do I sort this list of tuples by both values?

六月ゝ 毕业季﹏ 提交于 2019-12-10 18:54:25

问题


I have a list of tuples: [(2, Operation.SUBSTITUTED), (1, Operation.DELETED), (2, Operation.INSERTED)]

I would like to sort this list in 2 ways:

First by its 1st value by ascending value, i.e. 1, 2, 3... etc Second by its 2nd value by reverse alphabetical order, i.e. Operation.SUBSTITITUTED, Operation.INSERTED, Operation, DELETED

So the above list should be sorted as:

[(1, Operation.DELETED), (2, Operation.SUBSTITUTED), (2, Operation.INSERTED)]

How do I go about sort this list?


回答1:


Since sorting is guaranteed to be stable, you can do this in 2 steps:

lst = [(2, 'Operation.SUBSTITUTED'), (1, 'Operation.DELETED'), (2, 'Operation.INSERTED')]

res_int = sorted(lst, key=lambda x: x[1], reverse=True)
res = sorted(res_int, key=lambda x: x[0])

print(res)

# [(1, 'Operation.DELETED'), (2, 'Operation.SUBSTITUTED'), (2, 'Operation.INSERTED')]



回答2:


In this particular case, because the order of comparison can be easily inverted for integers, you can sort in one time using negative value for integer key & reverse:

lst = [(2, 'Operation.SUBSTITUTED'), (1, 'Operation.DELETED'), (2, 'Operation.INSERTED')]
res = sorted(lst, key=lambda x: (-x[0],x[1]), reverse=True)

result:

[(1, 'Operation.DELETED'), (2, 'Operation.SUBSTITUTED'), (2, 'Operation.INSERTED')]

negating the integer key cancels the "reverse" aspect, only kept for the second string criterion.




回答3:


You can use this:

from operator import itemgetter
d = [(1, 'DELETED'), (2, 'INSERTED'), (2, 'SUBSTITUTED')]
d.sort(key=itemgetter(1),reverse=True)
d.sort(key=itemgetter(0))
print(d)



回答4:


Another way using itemgetter from operator module:

from operator import itemgetter

lst = [(2, 'Operation.SUBSTITUTED'), (1, 'Operation.DELETED'), (2, 'Operation.INSERTED')]

inter = sorted(lst, key=itemgetter(1), reverse=True)
sorted_lst = sorted(inter, key=itemgetter(0))

print(sorted_lst)

# [(1, 'Operation.DELETED'), (2, 'Operation.SUBSTITUTED'), (2, 'Operation.INSERTED')]                                


来源:https://stackoverflow.com/questions/49752739/how-do-i-sort-this-list-of-tuples-by-both-values

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