about sort a list with integer key

Fredrik Lundh fredrik at pythonware.com
Sun Jan 13 07:26:13 EST 2008


lotrpy wrote:

> key = int(itemgetter(0)) is wrong,  key = lambda x:int(x[0]) works.
> but s.b. told me itemgetter execute more quickly .

so you're more interested in speed than in correctness? ;-)

operator.itemgetter is a function factory that creates a *function* that 
fetches the given item from a sequence.  or in other words, typing

     func = itemgetter(0)

is pretty much the same thing as typing

     def func(seq):
         return seq[0]

given this, it should be fairly obvious what int(itemgetter(0)) does: it 
attemts to convert the *function* to an integer, which obviously doesn't 
work.

I'd stick to the lambda form if I were you.  It isn't only easier to 
understand for the Python layman, it also does the right thing.

</F>




More information about the Python-list mailing list