order = ['w','x','a','z']
[(object,'a'),(object,'x'),(object,'z'),(object,'a'),(object,'w')]
How do I sort the above list of tuples by the second element according the the key list provided by ‘order’?
UPDATE on 11/18/13:
I found a much better approach to a variation of this question where the keys are certain to be unique, detailed in this question: Python: using a dict to speed sorting of a list of tuples.
My above question doesn’t quite apply because the give list of tuples has two tuples with the key value of 'a'.
You can use
sorted, and give as thekeya function that returns the index of the second value of each tuple in theorderlist.Beware, this fails whenever a value from the tuples is not present within the
orderlist.Edit:
In order to be a little more secure, you could use :
This will put all entries with a key that is missing from
orderlist at the end of the resulting list.