Sorting a list depending of the indexes of another sorted list
Peter Otten
__peter__ at web.de
Mon Jan 21 10:10:17 EST 2008
Steven D'Aprano wrote:
>> 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']
> What bit are you suggesting is undocumented?
The lambda spits out the items in preferences in the same order as they
occur in that list. If hosts.sort(key=...) in its C-implemented decoration
phase would iterate over the items in hosts in, say, reverse order hosts
would not be sorted correctly. Here's an illustration in Python:
>>> def dsu(items, key, reorder=lambda x: x):
... for i in reorder(range(len(items))):
... items[i] = key(items[i]), items[i]
... items.sort()
... items[:] = [v for k, v in items]
... return items
...
>>> dsu([1,2,3], lambda x, n=iter("acb").next: n())
[1, 3, 2]
>>> dsu([1,2,3], lambda x, n=iter("acb").next: n(), reversed)
[3, 1, 2]
Peter
More information about the Python-list
mailing list