about sort a list with integer key

lotrpy lotrpy at gmail.com
Sun Jan 13 06:24:59 EST 2008


hi, if I want sort each line ,by the last part,of a file, below is the
source.
from operator import itemgetter
content = (line.split() for line in file('foo.txt', 'rb'))
for cursor, line in enumerate(sorted(content, key = itemgetter(-1),
reverse = True)):
    print cursor, ' '.join(line)
the content of foo.txt is
   21 job
   3 joke
the result is
0 3 joke
1 21 job

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 .



More information about the Python-list mailing list