list conversion question

Andrew Dalke adalke at mindspring.com
Sat Sep 4 19:55:49 CEST 2004


Paul McGuire wrote:
> Probably the fastest way to do this (since we are tweaking for
> speed) would be to just change the pairs list comp to "pairs = [(-value,
> offset) for (offset, value) in enumerate(hist)]", or your Py 2.4 key clause
> from "key=lambda pair: pair[1]" to "key=lambda pair: -pair[1]".

Ahh, right.  The new Python2.4 'sorted' also has a
"reversed" flag, so

 >>> hist = [ 0, 1, 0, 5, 43 ]
 >>> [pair[0] for pair in sorted(enumerate(hist),
...                             key=lambda pair: pair[1],
...                             reverse=True)]
[4, 3, 1, 0, 2]
 >>>

This isn't the same as as reverse() after the sort(),

pairs = [(value, offset) for (offset, value) in enumerate(hist)]
pairs.sort()
indexes = [offset for (value, offset) in pairs]
indexes.reverse()

or

list(reversed([pair[0] for pair in sorted(enumerate(hist),
                                      key=lambda pair: pair[1])]))

Both of these give

[4, 3, 1, 2, 0]

The difference is that sort is now a guaranteed
stable sort.  Using 'reverse=True' means the index
to the first 0 (at index 0) appears before the index
to the seond 0 (at index 2).  Using reverse() or
reversed() flips that direction.

				Andrew
				dalke at dalkescientific.com



which would give


[0, 2, 1, 3, 4]

				Andrew



More information about the Python-list mailing list