sort one list using the values from another list

Ron Adam rrr at ronadam.com
Sun Feb 26 16:33:32 EST 2006


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.

Ron




More information about the Python-list mailing list