Getting sorting order

Peter Otten __peter__ at web.de
Mon Jun 30 11:11:30 CEST 2008


leodp wrote:

> I cannot find anything on this:
> I have a few lists, and would like to sort one of them (sorting-master
> list).
> Then I would like to sort all other lists according to how the first
> one was sorted (sorting-slave lists).
> 
> Is there a standard way to do that?
> From what I know sort() and sorted() do not return the order of
> sorting.
> Maybe I have to write some more code.

Or provide a better explanation and an example. Do you mean something like
this?

>>> master = [1,3,5,2,4,6]
>>> slave = [1,2,3,4]
>>> slave.sort(key=master.index)
>>> slave
[1, 3, 2, 4]

It can be made more robust and efficient with an intermediate dictionary:

>>> master_dict = dict((v, i) for i, v in enumerate(master))
>>> slave = ["yadda",1,2,3,6,42]
>>> slave.sort(key=master_dict.get)
>>> slave
['yadda', 42, 1, 3, 2, 6]

Peter



More information about the Python-list mailing list