1

My code

b=[((1,1)),((1,2)),((2,1)),((2,2)),((1,3))] for i in range(len(b)): print b[i] Obtained output:
(1, 1)
(1, 2)
(2, 1)
(2, 2)
(1, 3)

how do i sort this list by the first element or/and second element in each index value to get the output as:
(1, 1)
(1, 2)
(1, 3)
(2, 1)
(2, 2)

OR

(1, 1)
(2, 1)
(1, 2)
(2, 2)
(1, 3)

It would be nice if both columns are sorted as shown in the desired output, how ever if either of the output columns is sorted it will suffice.

2 Answers 2

1

Try this: b = sorted(b, key = lambda i: (i[0], i[1]))

Sign up to request clarification or add additional context in comments.

Comments

0

The sorted builtin does this.

>>> sorted (b)
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2)]

This only sorts by the first element, to sort on the second

>>> sorted(b, key=lambda i: i[1])
[(1, 1), (2, 1), (1, 2), (2, 2), (1, 3)]

Also notice that Python doesn't allow this nested tuple; the paren inside a paren is reduced to just one.

>>> b=[((1,1)),((1,2)),((2,1)),((2,2)),((1,3))]
>>> b
[(1, 1), (1, 2), (2, 1), (2, 2), (1, 3)]

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.