sort one list using the values from another list

Ron Adam rrr at ronadam.com
Sun Feb 26 19:22:46 EST 2006


Alex Martelli wrote:
> Ron Adam <rrr at ronadam.com> wrote:
> 
>> bearophileHUGS at lycos.com wrote:
>>> Your solution Steven Bethard looks very intelligent, here is a small
>>> speed test, because sorting a list according another one is a quite
>>> common operation.
>>> (Not all solutions are really the same, as Alex has shown).
>> Try this one.
>>
>> def psort10(s1, s2):
>>      d = dict(zip(s2,s1))
>>      s1[:] = (d[n] for n in sorted(d.keys()))
>>
>> It's faster on my system because d.keys() is already sorted.  But that
>> may not be the case on other versions of python.
> 
> If there are duplicates in s2, this solution will silently lose some
> items from s1.  I would at least include an assert len(s2)==len(d) as
> the second statement to get some insurance that this doesn't occur.
> 
> 
> Alex

Good point,  and a function that only works part time isn't good.  ;-)




More information about the Python-list mailing list