sort one list using the values from another list

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


bearophileHUGS at lycos.com wrote:
>> It's faster on my system because d.keys() is already sorted.  But that may not be the case on other versions of python.<
> 
> In my version it's a little slower. But what system are you using where
> keys is already sorted? IronPython maybe?
> 
> Bye,
> bearophile 


Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on 
win32

I was a bit surprised by them being sorted.  I just happend to try 
d.keys() in place of s2, and it sped up.  I was expecting it to be a bit 
slower.

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.  ;-)

Like Alex pointed out you need to make sure there aren't duplicates in 
the list used for keys.

def psort10(s1, s2):
     d = dict(zip(s2,s1))
     assert len(d) == len(s1)
     s1[:] = (d[n] for n in sorted(d.keys()))

Ron



More information about the Python-list mailing list