Sorting a list depending of the indexes of another sorted list

Peter Otten __peter__ at web.de
Mon Jan 21 03:53:10 EST 2008


Santiago  Romero wrote:

>  I'm trying to sort both lists so that they end like this:
> 
> preferences = [10, 20, 30]
> hosts = [ "mx1.domain.com", "mx2.domain.com",
> "anotherhost.domain.com" ]
> 
>  I want to sort hosts list depending on the numeric order of
> "preferences".

The following relies on undocumented (I hope) behaviour:

>>> preferences = [10, 30, 20]
>>> hosts = [ "mx1.domain.com", "anotherhost.domain.com", "mx2.domain.com"]
>>> hosts.sort(key=lambda x, p=iter(preferences).next: p())
>>> preferences.sort()
>>> hosts
['mx1.domain.com', 'mx2.domain.com', 'anotherhost.domain.com']
>>> preferences
[10, 20, 30]

Don't do it, use a list of tuples as already suggested.

Peter



More information about the Python-list mailing list