sort one list using the values from another list
Ron Adam
rrr at ronadam.com
Mon Feb 27 18:21:00 EST 2006
Scott David Daniels wrote:
> Ron Adam wrote:
>> Ron Adam wrote:
>> This probably should be:
>>
>> def psort11(s1, s2):
>> d = dict(zip(s2,s1))
>> assert len(d) == len(s1)
>> s1[:] = list(d[v] for v in sorted(d))
>
> You could do this to avoid all of those lookups:
>
> def psort_xx(s1, s2):
> pairs = sorted(dict(zip(s2, s1)).iteritems())
> assert len(pairs) == len(s1)
> s1[:] = [s1_value for s2_value, s1_value in pairs]
This version takes twice as long on my system, although the result may
vary on other platforms. Dictionary lookups are very fast.
Although replacing zip with izip cut the time in half.
def psort11(s1, s2):
d = dict(izip(s2,s1))
assert len(d) == len(s1)
s1[:] = list(d[v] for v in sorted(d))
Ron
More information about the Python-list
mailing list