Sorting x lists based on one list ... maybe an example would make sense:

Peter Otten __peter__ at web.de
Tue May 17 11:04:44 EDT 2005


> Philippe C. Martin wrote:
> 
>> I'm looking for an easy algorithm - maybe Python can help:
>> I start with X lists which intial sort is based on list #1.
>> I want to reverse sort list #1 and have all other lists sorted
>> accordingly.

One way, using a helper list with indices:

>>> l1 = ['a','b','c']
>>> l2 = ['toto','titi','tata'] # 'toto' refers to 'a', 'titi' to b' ....
>>> l3 = ['foo','bar','doe'] # 'foo' refers to 'a' ........
>>> indices = sorted(range(len(l1)), key=l1.__getitem__, reverse=True)
>>> for items in l1, l2, l3:
...     items[:] = [items[i] for i in indices]
...
>>> l1
['c', 'b', 'a']
>>> l2
['tata', 'titi', 'toto']
>>> l3
['doe', 'bar', 'foo']

Another way would be to merge the three lists into one of 3-tuples, sort,
and unmerge, similarly to the DSU pattern -- which raises the question: why
are you using three lists in the first place?

Peter





More information about the Python-list mailing list