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!
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)
Use key
to select the second element in the list, and reverse
to change direction:
>>> l=[['a',[10]], ['b',[1]], ['c',[5,10]], ['d',[5,1,-10], ['e',[5,1,-1]]]
>>> sorted(l, key=lambda e:e[1], reverse=True)
[['a', [10]], ['c', [5, 10]], ['e', [5, 1, -1]], ['d', [5, 1, -10]], ['b', [1]]]
Lists are sorted by comparing their elements in order, just like a lexicon or regular dictionary. It's called 'lexographical comparison'.
精彩评论