list comprehensions: sorting?

Skip Montanaro skip at pobox.com
Wed Sep 5 21:52:05 EDT 2001


    Clark> Here is the best I can think of...

    Clark>   newlist = [x for x in mylist if x[4]]
    Clark>   newlist.sort(lambda x,y: cmp(x[2],y[2]))

    Clark> That's ok... but I'd like to have a nicer way
    Clark> to say "sort by column #2" ; preferably as part
    Clark> of the longer expression...

The most common way to do this is to turn each element list into two lists,
ordered the way you want.  Suppose you have this list:

    mylist = [["a", "b", "c"],
              ["cat", "aardvark", "rat"],
              ["judy", "judy", "judy"],
              ["Guido", "Barry", "Sam"]]

and you want to sort by the second element of each sublist ("b", "aardvark",
etc).  Generate a list that contains the fields in the order you want:

    sortinglist = [(x[1:2] + x[0:1] + x[2:], x) for x in mylist]

Sort it:

    sortinglist.sort()

Then extract the original list:

    mylist = [x[1] for x in sortinglist]

When all is said and done, mylist is

    [['Guido', 'Barry', 'Sam'],
     ['cat', 'aardvark', 'rat'],
     ['a', 'b', 'c'],
     ['judy', 'judy', 'judy']]

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list