Getting sorting order

Peter Otten __peter__ at web.de
Mon Jun 30 12:06:53 CEST 2008


leodp wrote:

> 
>> Or provide a better explanation and an example. Do you mean something
>> like this?
>>
> 
> Hi Peter,
> a small example:
> 
> master=[1,4,3,2]
> slave1=['d','c','b','a']
> slave2=[1,2,3,4]
> 
> master.sort() # this is ok, but does not return infos on how the list
> was sorted
> slave1.sort(key=_maybe_something_here_referring_to_master_)
> slave2.sort(key=_maybe_something_here_referring_to_master_)
> 
> Then I should get:
> master=[1,2,3,4]
> slave1=['d','a','b','c']
> slave2=[1,4,3,2]
> 
> 
> Hope it is more clear now.
> Thanks, leodp

You need a helper list (called master_index in the example below):

>>> master=[1,4,3,2]
>>> slave1=['d','c','b','a']
>>> slave2=[1,2,3,4]
>>> master_index = range(len(master))
>>> master_index.sort(key=master.__getitem__)
>>> master[:] = [master[i] for i in master_index]
>>> slave1[:] = [slave1[i] for i in master_index]
>>> slave2[:] = [slave2[i] for i in master_index]
>>> master
[1, 2, 3, 4]
>>> slave1
['d', 'a', 'b', 'c']
>>> slave2
[1, 4, 3, 2]


If you don't care about list object identity you can use
master = [...] instead of master[:] = [...] etc.

Peter




More information about the Python-list mailing list