sort one list using the values from another list

Duncan Booth duncan.booth at invalid.invalid
Sun Feb 26 12:27:04 EST 2006


Steven Bethard wrote:

> Here's a solution that makes use of the key= argument to sorted():
> 
> >>> A = ['hello','there','this','that']
> >>> B = [3,4,2,5]
> >>> indices = range(len(A))
> >>> indices.sort(key=B.__getitem__)
> >>> [A[i] for i in indices]
> ['this', 'hello', 'there', 'that']
> 
> Basically, it sorts the indices to A -- [0, 1, 2, 3] -- in the order 
> given by B, and then selects the items from A in the appropriate order.
> 
> 

That's impressive. I'm sure like a lot of other people I looked at the 
question and thought it ought to be possible to use key to get this result 
without a load of zipping and unzipping but just couldn't quite see it.

If you combine your technique with 'sorted', you get the one line version:

>>> [A[i] for i in sorted(range(len(A)), key=B.__getitem__)]
['this', 'hello', 'there', 'that']




More information about the Python-list mailing list