sort one list using the values from another list

Kent Johnson kent at kentsjohnson.com
Sun Feb 26 11:30:33 EST 2006


Brian Blais wrote:
> Hello,
> 
> I have two lists, one with strings (filenames, actually), and one with a 
> real-number
> rank, like:
> 
> A=['hello','there','this','that']
> B=[3,4,2,5]
> 
> I'd like to sort list A using the values from B, so the result would be 
> in this example,
> 
> A=['this','hello','there','that']

Here are two ways:
  >>> A=['hello','there','this','that']
  >>> B=[3,4,2,5]
  >>> zip(*sorted(zip(B,A)))[1]
('this', 'hello', 'there', 'that')

  >>> [a for b,a in sorted(zip(B,A))]
['this', 'hello', 'there', 'that']

I prefer the second one, I think it is more readable, will use less 
memory (doesn't have to create a new list B in the final step) and it's 
even faster on my computer:

D:\Projects\CB>python -m timeit -s 
"A=['hello','there','this','that'];B=[3,4,2,5]" "zip(*sorted(zip(B,A)))[1]"
100000 loops, best of 3: 6.29 usec per loop

D:\Projects\CB>python -m timeit -s 
"A=['hello','there','this','that'];B=[3,4,2,5]" "[a for b,a in 
sorted(zip(B,A))]"
100000 loops, best of 3: 5.53 usec per loop

(I'm bored this morning :-)

There's probably a clever way to do it using the key parameter to sort 
but I can't think of it...
> 
> The sort method on lists does in-place sorting.  Is there a way to do 
> what I want here?

The example above does not sort in place, if you want it to be in place use
A[:] = [a for b,a in sorted(zip(B,A))]

Kent



More information about the Python-list mailing list