0

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

1 Answer 1

1

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.