sorting two corresponding lists?
saketh.bhamidipati at gmail.com
Mon Apr 20 18:25:39 CEST 2009
On Apr 20, 12:10 pm, Esmail <ebo... at hotmail.com> 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?
Why not use a dictionary instead of two lists? Then you can sort the
dictionary by value -- e.g.
d = dict(zip(items, values))
sorted_items = sorted(d.iteritems(), key=lambda (k,v): (v,k))
This produces a list of pairs, but demonstrates the general idea.
More information about the Python-list