sort one list using the values from another list

Ron Adam rrr at ronadam.com
Sun Feb 26 21:01:51 EST 2006


Alex Martelli wrote:
> Ron Adam <rrr at ronadam.com> wrote:
>    ...
>> Considering the number time I sort keys after getting them, It's the 
>> behavior I would prefer.  Maybe a more dependable dict.sortedkeys() 
>> method would be nice.  ;-)
> 
> sorted(d) is guaranteed to do exactly the same thing as sorted(d.keys())
> AND to be faster (would be pretty weird if it weren't faster...!).
> 
> E.g., ...:
> 
> helen:~ alex$ python -mtimeit -s'd=dict(enumerate("tarazoplay"))'
> 'sorted(d.keys())'
> 100000 loops, best of 3: 6.82 usec per loop
> 
> helen:~ alex$ python -mtimeit -s'd=dict(enumerate("tarazoplay"))'
> 'sorted(d)'
> 100000 loops, best of 3: 5.98 usec per loop
> 
> 
> Alex


Yes, it did decrease it.  And simplified it as well. ;)


def psort11(s1, s2):
     d = dict(zip(s2, s1))
     assert len(d) == len(s1)
     sorted(d)
     s1[:] = d.values()


psort1 0.554 s
psort2 0.727 s
psort3 0.295 s
psort4 0.293 s
psort5 0.831 s
psort6 0.438 s
psort7 0.575 s
psort8 0.845 s
psort9 0.424 s
psort10 0.235 s
psort11 0.206 s






More information about the Python-list mailing list