sorting list of tuples by arbitrary key

前端 未结 1 1256
暖寄归人
暖寄归人 2021-02-14 09:32
order = [\'w\',\'x\',\'a\',\'z\']
[(object,\'a\'),(object,\'x\'),(object,\'z\'),(object,\'a\'),(object,\'w\')]

How do I sort the above list of tuples b

相关标签:
1条回答
  • 2021-02-14 09:52

    You can use sorted, and give as the key a function that returns the index of the second value of each tuple in the order list.

    >>> sorted(mylist,key=lambda x: order.index(x[1]))
    
    [('object', 'w'), ('object', 'x'), ('object', 'a'), ('object', 'a'), ('object', 'z')]
    

    Beware, this fails whenever a value from the tuples is not present within the order list.

    Edit:

    In order to be a little more secure, you could use :

    sorted(mylist,key=lambda x: x[1] in order and order.index(x[1]) or len(order)+1)
    

    This will put all entries with a key that is missing from order list at the end of the resulting list.

    0 讨论(0)
提交回复
热议问题