sorting two corresponding lists?

Arnaud Delobelle arnodel at googlemail.com
Mon Apr 20 15:43:42 EDT 2009


Esmail <ebonak at hotmail.com> writes:

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

One way I have not seen in any reply is to sort the indices first.

>>> values = [5, 2, 7, 1]
>>> items = ['apple', 'car', 'town', 'phone']

Create a list of all indices:

>>> indices = range(len(values))
>>> indices
[0, 1, 2, 3]

Sort the indices according to the value at each index:

>>> indices.sort(key=lambda i: values[i], reverse=True)
>>> indices
[2, 0, 1, 3]

Now you can get the sorted values and items without further sorting:

>>> [values[i] for i in indices]
[7, 5, 2, 1]
>>> [items[i] for i in indices]
['town', 'apple', 'car', 'phone']

This can be spelt:

>>> map(values.__getitem__, indices)
[7, 5, 2, 1]
>>> map(items.__getitem__, indices)
['town', 'apple', 'car', 'phone']
>>> 

HTH

-- 
Arnaud



More information about the Python-list mailing list