Quoting Esmail <ebo...@hotmail.com>:
> 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]
I've used this sometimes:
=== [untested] ===
sorted_pairs = sorted(zip(values,items))
values = [value for value, _ in sorted_pairs]
items = [item for _, item in sorted_pairs]
===
You could also do something like this, if you don't mind the extra indirection:
=== [also untested] ===
indices = sorted(range(len(values)), key = lambda i: values[i])
# and then access the values as
print "first value", values[indices[0]]
print "first item", items[indices[0]]
===
Keep in mind that both cases keep the original lists unsorted. I guess you could
use "values[:] = " instead of "values = " on the first option to simulate a
sort_in_place.
I usually prefer the first form.
--
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie
--
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie
--
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba
http://www.universidad2010.cu
--
http://mail.python.org/mailman/listinfo/python-list