sorting two corresponding lists?

Diez B. Roggisch deets at nospam.web.de
Mon Apr 20 12:23:01 EDT 2009


Esmail wrote:

> Hello all,
> 
> I wonder if someone could help me with sorting two corresponding lists.
> 
> For instance the first list contains some items, and the second list
> contains their value (higher is better)
> 
> items = [apple, car, town, phone]
> values = [5, 2, 7, 1]
> 
> I would like to sort the 'items' list based on the 'values' list so
> that I end up with the following two list:
> 
> items = [town, apple, car, phone]
> values = [7, 5, 2, 1]
> 
> So I would like to keep the corresponding value still corresponding
> after the sorting.
> 
> Is there an easy/nice/Pythonic way to do this?

items = zip(*sorted(zip(values, items)))[1]

To better understand this please note that

a = [1, 2]
b = [3, 4]

zip(*zip(a, b)) == a, b

or, in other words, zip(*argument) is the inverse of an argument created by
zip (under the assumption the a and b have equal length)

Diez



More information about the Python-list mailing list