views:

84

answers:

3

I have some data either in list contains lists, or list contains tuples.

data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]

And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). What is the common way to do this? Should I store tuples or lists in my list? Since tuples are more inflexible. Thanks.

+6  A: 
sorted_by_second = sorted(data, key=lambda tup: tup[1])

or:

data.sort(key=lambda tup: tup[1])  // sorts in place
Stephen
+4  A: 

For tuples and/or lists, this will do:

import operator
data.sort(key=operator.itemgetter(1))

or

sorted(data, key=operator.itemgetter(1))
Adam Bernier
+2  A: 

Stephen's answer is the one I'd use. For completeness, here's the DSU (decorate-sort-undecorate) pattern with list comprehensions:

decorated = [(tup[1], tup) for tup in data]
decorated.sort()
undecorated = [tup for second, tup in sorted_decorated]

Or, more tersely:

[b for a,b in sorted((tup[1], tup) for tup in data)]

As noted in the Python Sorting HowTo, this has been unnecessary since Python 2.4, when key functions became available.

tcarobruce
Thanks for the answer!
Stan