about sort a list with integer key

Hrvoje Niksic hniksic at xemacs.org
Sun Jan 13 13:32:48 CET 2008


lotrpy <lotrpy at gmail.com> writes:

> if i want sort each line by the first part,(it's a integer, in fact).
> don't know how to do it with itemgetter.
> key = int(itemgetter(0)) is wrong,  key = lambda x:int(x[0]) works.
> but s.b. told me itemgetter execute more quickly .

Use lambda when it works better for you, the speed difference is
marginal in practice anyway.  itemgetter is not (and was never
intended to be) a general substitute for functions, as you've
discovered.

The marginal speed difference between itemgetter and an explicit
lambda that does the subscripts is a consequence of itemgetter being
written in C, meaning it avoids the creation of a Python stack frame,
etc.  Combining int(...) with this operation requires coding the key
function in Python, which removes itemgetter's advantage.  In other
words, you cannot retain itemgetter's speed advantage with more
complex keys.  If the sorting performance is a problem for you, please
give more details about what you're doing -- there might be better
ways to speed up the code.



More information about the Python-list mailing list