Reputation: 3
I am new in python,I want to sort a list of lists in python in non-decreasing order by the first index but if the first index holds equal values sort by the second index in decreasing order
ex [[3,3],[3,2],[1,3]]
output [[1,3],[3,3][3,2]]
ex2[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
output[[4, 4], [5, 2],[5, 0], [6, 1], [7, 1],[7, 0]]
in c++ I used this function as key
static bool lessThan(vector<int> &l , vector<int> &r)
{
if (r[0] == l[0])
return l[1]>r[1];
return l[0]<r[0];
}
but on python key function has different behaviour
Upvotes: 0
Views: 135
Reputation: 92440
Since you are just sorting numbers, you can take a shortcut and just take the negative of the second element in the tuple:
l = [[3,3],[3,2],[1,3], [3,5], [3,0], [3, -1]]
sorted(l, key=lambda x: (x[0], -x[1]))
# [[1, 3], [3, 5], [3, 3], [3, 2], [3, 0], [3, -1]]
Upvotes: 1