'Sort a list according to the sublists [duplicate]
I am given a list:
lst = [[7090, 1.286], [7486, 2.569], [7571, 0.091]]
I want to sort this list in ascending order according to the second numbers of the sublists (namely, 1.286, 2.569, 0.091) so it looks like [[7571, 0.091], [7090, 1.286], [7486, 2.569]]. How should I do it by using python?
Solution 1:[1]
You can do this with Python lists build in sort function.
lst = [[7090, 1.286], [7486, 2.569], [7571, 0.091]]
A typical .sort call would sort it based on the first item per sublist, in ascending order.
lst.sort()
print(lst) # returns [[7090, 1.286], [7486, 2.569], [7571, 0.091]]
To sort it on the second item we can add the following:
lst.sort(key=lambda e: e[1])
print(lst) # returns [[7571, 0.091], [7090, 1.286], [7486, 2.569]]
The key passed to the sort function here takes in each sublist as parameter e and used the second element to sort.
Solution 2:[2]
Use the key parameter to sort (or sorted) to specify what you want to sort by.
sorted(lst, key=lambda item: item[1])
# => [[7571, 0.091], [7090, 1.286], [7486, 2.569]]
Alternately, you can use a predefined function from operator — this is equivalent:
from operator import itemgetter
sorted(lst, key=itemgetter(1))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Amadan |
