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

前端 未结 4 930
被撕碎了的回忆
被撕碎了的回忆 2021-01-20 15:58

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:

4条回答
  •  一个人的身影
    2021-01-20 16:08

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

提交回复
热议问题