sorting two corresponding lists?

Peter Otten __peter__ at web.de
Tue Apr 21 08:31:51 CEST 2009


Esmail wrote:

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


An exotic option:

>>> values = [5, 2, 7, 1]
>>> items = [apple, car, town, phone]
>>> items.sort(key=lambda item, next=iter(values).next: next(),
reverse=True)
>>> values.sort(reverse=True)
>>> items
[town, apple, car, phone]
>>> values
[7, 5, 2, 1]

Peter



More information about the Python-list mailing list