sort one list using the values from another list

Scott David Daniels scott.daniels at acm.org
Mon Feb 27 14:04:06 EST 2006


Ron Adam wrote:
> Ron Adam wrote:
>> 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()

Dictionaries are not ordered, the "sorted" line does nothing except produce
a sorted list of the dictionary's keys which is ignored.

> This probably should be:
> 
> def psort11(s1, s2):
>     d = dict(zip(s2,s1))
>     assert len(d) == len(s1)
>     s1[:] = list(d[v] for v in sorted(d))

You could do this to avoid all of those lookups:

      def psort_xx(s1, s2):
          pairs = sorted(dict(zip(s2, s1)).iteritems())
          assert len(pairs) == len(s1)
          s1[:] = [s1_value for s2_value, s1_value in pairs]


-- 
-Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list