I have some data either in a list of lists or a list of tuples, like this:
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?
itemgetter()
is somewhat faster thanlambda tup: tup[1]
, but the increase is relatively modest (around 10 to 25 percent).(IPython session)
or:
Stephen's answer is the one I'd use. For completeness, here's the DSU (decorate-sort-undecorate) pattern with list comprehensions:
Or, more tersely:
As noted in the Python Sorting HowTo, this has been unnecessary since Python 2.4, when key functions became available.
Without lambda:
I just want to add to Stephen's answer if you want to sort the array from high to low, another way other than in the comments above is just to add this to the line:
and the result will be as follows: