gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:29:20 25 4
gpt4 key购买 nike

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

我想用两种方式对这个列表进行排序:

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

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

[(1, Operation.DELETED), (2, Operation.SUBSTITED), (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')]

关于python - 如何按这两个值对元组列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49752739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com