I am looking to sort a list of tuple starting with the second item then by the first item. This is not a duplicate from Sort tuple by first then second then third, because this post is about first then second and not second then first.
Coming from a C# background, I would have lot to find something like OrderBy+ThenBy.
I could write my own and ship it. Python is battery included, I am sure there is a better way to achieve this.
mcve with unit tests:
def sort_tuples_by_second(inputs):
return sorted(inputs, key=lambda item: item[1])
class TestStringMethods(unittest.TestCase):
# both passed
def test_sort_tuples_by_second(self):
tuples = [(1, 1), (1, 2), (1, 0), (0, 9)]
actuals = sort_tuples_by_second(tuples)
self.assertEqual(actuals, [(1, 0), (1, 1), (1, 2), (0, 9)])
letters = [("a", "a"), ("b", "c"), ("c", "b"), ("a", "z")]
actuals = sort_tuples_by_second(letters)
self.assertEqual(actuals, [("a", "a"), ("c", "b"), ("b", "c"), ("a", "z")])
# both failed
def test_sort_tuples_by_second_then_by_first(self):
tuples = [(1, 1), (4, 1), (3, 1), (1, 9), (0, 9)]
actuals = sort_tuples_by_second(tuples)
self.assertEqual(actuals, [(1, 1), (3, 1), (4, 1), (0, 9), (1, 9)])
letters = [("b", "a"), ("a", "a")]
actuals = sort_tuples_by_second(letters)
self.assertEqual(actuals, [("a", "a"), ("b", "a")])