Reputation: 1
What's the best way to sort a list of tuples of (x, y)
's. I want to sort in terms of x
's but when there are x
's of the same values, I want to break and sort in terms of y
.
Upvotes: 0
Views: 315
Reputation: 160427
For a given list of two element tuples sharing the first x
value and differing in y
values:
t = [(1, 2), (1, 1), (1, 5), (2, 3), (2, 6)]
You can sort based on your criteria simply by sorted
(or sort
) since tuples
(inside the list) considers all elements while sorting:
>>> sorted(t)
[(1, 1), (1, 2), (1, 5), (2, 3), (2, 6)]
That is, conflicts at the first matching value are resolved by examining the next value in the sequence until one of the values is smaller than the other (i.e lexicographical sorting).
If no value is found to resolve the conflict, Python is going to retain the ordering as is found in the input sequence. This is another characteristic of sorting called stability.
Upvotes: 1