sort one list using the values from another list

Alex Martelli aleaxit at yahoo.com
Sun Feb 26 16:42:04 EST 2006


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



More information about the Python-list mailing list