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
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.