Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list by checking values in a sublist in python?

I have a list of lists in the following format:

[['a',[10]], ['b',[1]], ['c',[5,10]], ['d',[5,1,-10]], ['e',[5,1,-1]]]

I would like to sort if in an efficient way in python using the numeric list elements, matching the first element, and when it is the same, use the second, and so on. The result would be something like (I need reverse order this time):

['a',[10]]
['c',[5,10]]
['e',[5,1,-1]]
['d',[5,1,-10]
['b',[1]]

Thanks!

like image 484
Josep Valls Avatar asked May 20 '11 08:05

Josep Valls


2 Answers

I think lists compare like you want, by default, if inverted:

>>> data = [['a',[10]], ['b',[1]], ['c',[5,10]], ['d',[5,1,-10]], ['e',[5,1,-1]]
>>> sorted(data, reverse = True, key = lambda pair: pair[1])
[['a', [10]], ['c', [5, 10]], ['e', [5, 1, -1]], ['d', [5, 1, -10]], ['b', [1]]]

You had a bracketing error in your input list, it's fixed in the code above.

like image 68
unwind Avatar answered Sep 22 '22 09:09

unwind


>>> from operator import itemgetter
>>> L=[['a',[10]], ['b',[1]], ['c',[5,10]], ['d',[5,1,-10]], ['e',[5,1,-1]]]
>>> sorted(L, key=itemgetter(1), reverse=True)
[['a', [10]], ['c', [5, 10]], ['e', [5, 1, -1]], ['d', [5, 1, -10]], ['b', [1]]]
>>> 

I'd use itemgetter(1) here, which is roughly equivalent to the lambda function in the other answers. This effectively does the sort with the key being the sublists since they are item number 1. (item number 0 is the letters a-e)

like image 36
John La Rooy Avatar answered Sep 22 '22 09:09

John La Rooy