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

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

    0 讨论(0)
  • 2021-01-20 16:04

    Another way using itemgetter from operator module:

    from operator import itemgetter
    
    lst = [(2, 'Operation.SUBSTITUTED'), (1, 'Operation.DELETED'), (2, 'Operation.INSERTED')]
    
    inter = sorted(lst, key=itemgetter(1), reverse=True)
    sorted_lst = sorted(inter, key=itemgetter(0))
    
    print(sorted_lst)
    
    # [(1, 'Operation.DELETED'), (2, 'Operation.SUBSTITUTED'), (2, 'Operation.INSERTED')]                                
    
    0 讨论(0)
  • 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')]
    
    0 讨论(0)
  • 2021-01-20 16:27

    You can use this:

    from operator import itemgetter
    d = [(1, 'DELETED'), (2, 'INSERTED'), (2, 'SUBSTITUTED')]
    d.sort(key=itemgetter(1),reverse=True)
    d.sort(key=itemgetter(0))
    print(d)
    
    0 讨论(0)
提交回复
热议问题