1

I have the following array:

[[8, 1], [1, 1], [3, 1], [8, 1], [4, 0], [2, 0]]

How to sort the array based on the first value of the element and if second element equal to 1. I tried the following way,

sorted(x,key=lambda x:(x[0] and x[1]==1))

But I got this result:

[[10, 0], [5, 0], [5, 1], [2, 1], [1, 1], [8, 1]]
3
  • 2
    What is your expected output? Commented Feb 5, 2021 at 5:33
  • Actually, I want the array to be sorted based on the first element and the elements in x with x[i][1] ==1 to be in the last Commented Feb 5, 2021 at 5:35
  • 2
    It would be useful if you added the expected output as well, the explanation is still somehow unclear, Commented Feb 5, 2021 at 5:37

1 Answer 1

1
x[0] and x[1] == 1

This is a logical expression which will either evaluate either as True (if x[0] != 0 and x[1] == 1) or False. So your sort key can only take two possible values.

By my understanding, what you want is:

  • all cases where x[1] == 1 to appear after all the cases where x[1] != 1
  • subject to above, outputs to be sorted by x[0]

You can't do this easily with a one-dimensional key. To understand why, think about the range of possible inputs in between [-Inf,0] and [Inf,0] and the range between [-Inf,1] and [Inf,1].

Each of these ranges is infinitely large in both directions. If you want to sort them with a one-dimensional key, you somehow need to map two double-endedly infinite ranges onto one number line.

This isn't impossible - if you really had to do it that way, there are tricks you could use to make that happen. But it's a very roundabout way to solve the problem.

It's much easier just to use a two-dimensional key. The sort function checks the zero'th position of a tuple first, and only goes to the first position as a tiebreaker. So, because the value of x[1] takes priority in the sort order you want, the zeroth entry of the tuple is based on x[1] and the first is based on x[0], like this:

x=[[8, 1], [1, 1], [3, 1], [8, 1], [4, 0], [2, 0]]
sorted(x,key=lambda x:(x[1]==1,x[0]))

Output:

[[2, 0], [4, 0], [1, 1], [3, 1], [8, 1], [8, 1]]
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, it worked after changing the order
@Tonystark The other important part besides changing the order is that your key is now a tuple, not a single value.
What is the difference between a tuple and single value while sorting. Also can we add more conditions in the tuple?
@Tonystark I'll expand on that question in my answer, give me a moment.
@Tonystark I'm not sure what you're asking about adding more conditions.

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.