1

I like to have a Python 2D array sorted by based on the first column ascending than the second column descending and the third column ascending. So, the sort function will first try to sort the items on the first column, if the value of the first column is same, then it will try to sort based on the second column value descending, even if the second column value is same, then it will try to sort based on the third value in ascending order.

So, if I have a Python array like this-

[[15, 18, 2], [1, 3, 3], [7, 10, 8], [1, 2, 1], [8, 11, 5], [8, 10, 5], [1, 6, 1], [1, 6, 2]]

Then for the given array, the output should be like this-

[[1, 6, 1], [1, 6, 2] [1, 3, 3], [1, 2, 1], [7, 10, 8], [8, 11, 5], [8, 10, 5], [15, 18, 2]]

I have to use python lambda function for this. What I have done is-

intervals = [[15, 18, 2], [1, 3, 3], [7, 10, 8], [1, 2, 1], [8, 11, 5], [8, 10, 5], [1, 6, 1], [1, 6, 2]]
................
................
intervals.sort(key=lambda x: x[2] or x[1] and x[0])

After this, what I am getting is like this-

[[1, 2, 1], [1, 6, 1], [15, 18, 2], [1, 6, 2], [1, 3, 3], [8, 11, 5], [8, 10, 5], [7, 10, 8]]

Which is not as expected. Is there any way of finding what I need to have?

Thanks in advance for helping.

1 Answer 1

2

Because your values are numeric, you can negate them to sort descending, so to sort according to x[0] ascending, x[1] descending and x[2] ascending you just need to sort on the tuple (x[0], -x[1], x[2]):

intervals = [[15, 18, 2], [1, 3, 3], [7, 10, 8], [1, 2, 1], [8, 11, 5], [8, 10, 5], [1, 6, 1], [1, 6, 2]]

intervals.sort(key=lambda x:(x[0], -x[1], x[2]))
print(intervals)

Output:

[[1, 6, 1], [1, 6, 2], [1, 3, 3], [1, 2, 1], [7, 10, 8], [8, 11, 5], [8, 10, 5], [15, 18, 2]]
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.