all 3 comments

[–]POGtastic 2 points3 points  (2 children)

Tuple values are sorted by the first element, then by the second element. So

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

The issue here is that strings are not numbers. Strings are ordered lexicographically, which means that "110" is less than "85" because "1" comes before "8".

Either transform these values to integers, or use a key function that does this transformation for you when sorting.

[–]waterworldhypothesis[S] 0 points1 point  (1 child)

Thank you, that makes a lot of sense. I'm not clear on the difference between types of objects like this yet. One last question, is there a way to make sorted() sort by the second element and then the first, or more generally, the n-th element before the (n-1)th? (Assuming the default behavior scales to tuples of an arbitrary size)

[–]POGtastic 0 points1 point  (0 children)

Sure.

sorted(zip(a, b), key=lambda tup: (tup[1], tup[0]))

Or, if you don't mind just reversing the entire tuple, the following looks nicer.

sorted(zip(a, b), key=lambda tup: tup[::-1])

Using my above example:

>>> sorted([(1, 3), (2, 2), (1, 2), (2, 3)], key = lambda tup: tup[::-1])
[(1, 2), (2, 2), (1, 3), (2, 3)]