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

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

我想以两种方式对此列表进行排序:

首先是它的第一个值乘以升值,即1,2,3 ……等
其次是按反向字母顺序排列的第二个值,即Operation.SUBSTITITUTED,Operation.INSERTED,Operation,DELETED

所以上面的列表应该排序为:

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

我如何排序此列表?

最佳答案 由于排序为
guaranteed to be stable,您可以分两步完成:

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