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!
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.
>>> 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With