0

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")])

Try it online!

aloisdg
  • 22,270
  • 6
  • 85
  • 105

1 Answers1

1

You are looking for a builtin way and there are two! You could have found them by looking at how python dev sort others data structures. As example, some hints are present on sort a list of dicts by x then by y. In there case, they sort by key:

list.sort(key=lambda item: (item['points'], item['time']))

Try it online!

or in you case with a tuple:

sorted(inputs, key=lambda item: (item[1], item[0]))

Python's HowTo offers an alternative:

from operator import itemgetter

sorted(inputs, key=itemgetter(1, 0))

Try it online!

aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • 1
    you asked and you answered why ?? – Amy Sep 02 '19 at 09:54
  • 2
    @Amy because I could not find the answer online. While writing the question, I resolved my problem. Now, I post it to help others. Read [It’s OK to Ask and Answer Your Own Questions](https://stackoverflow.blog/2011/07/01/its-ok-to-ask-and-answer-your-own-questions/) by one of Stack Overflow's founder. – aloisdg Sep 02 '19 at 09:57
  • great job keep it continue and thanks for answer – Amy Sep 02 '19 at 09:58
  • 3
    Actually, there are various questions that already cover the same topic, with this probably being the more close to this question: https://stackoverflow.com/questions/5212870/sorting-a-python-list-by-two-fields – musicamante Sep 02 '19 at 10:07
  • @musicamante I didnt find it before.I am glad this exist. I found it strange that my question wasnt already posted. Thank you for finding it! – aloisdg Sep 02 '19 at 10:20