Reputation: 124
I have a 2d list like this:
[
[abc, 5],
[abd, 21],
[abb, 10],
[abc, 3],
[abb, 15],
[abd, 20]
]
First: I need to sort the list in lexicographical order(which is fairly simple)
Second: If there are multiple same elements in the first column, sort the list(only the same elements) according to the second column(descending order).
So, I want a result like this:
[
[abb, 15],
[abb, 10],
[abc, 5],
[abc, 3],
[abd, 21],
[abd, 20]
]
Upvotes: 1
Views: 1170
Reputation: 736
Python's sort function is stable, which means that if two elements compare equal to each other, their relative positions don't change. Elements only switch positions if they compare unequal to each other.
Additionally, sorting takes an optional key
parameter, which is a function that determines which values the sort should compare. You can define a full function for this, but it's common to define a short lambda function if you're only going to use it once.
Put these together, and you can first sort the lists by their second elements, then sort them a second time by their first elements. The relative positions from the first sort will be maintained after the second.
a = [
['abc', 5],
['abd', 21],
['abb', 10],
['abc', 3],
['abb', 15],
['abd', 20]
]
# Sort by second element first, in descending order
a = sorted(a, key=lambda x: x[1], reverse=True)
# Then sort by first element, in ascending order
a = sorted(a, key=lambda x: x[0])
print(a) # [['abb', 15], ['abb', 10], ['abc', 5], ['abc', 3], ['abd', 21], ['abd', 20]]
Upvotes: 1
Reputation: 4864
The method is described in nauseating detail here: https://portingguide.readthedocs.io/en/latest/comparisons.html
Upvotes: 1