如何按两个值对该元组列表进行排序?

问题描述:

我有一个元组列表:[(2, Operation.SUBSTITUTED), (1, Operation.DELETED), (2, Operation.INSERTED)]

我想用2种方式对该列表进行排序:

I would like to sort this list in 2 ways:

首先以其第一个值递增,即1, 2, 3... etc 第二个是其第二个值,按相反的字母顺序排列,即Operation.SUBSTITITUTED, Operation.INSERTED, Operation, DELETED

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)]

如何对列表进行排序?

由于排序是

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')]