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

前端 未结 4 988
被撕碎了的回忆
被撕碎了的回忆 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:04

    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.

提交回复
热议问题