Python: Sort list of elements by first element, but if equal sort by original index

Issue

I have a list of elements that looks like this:

['3,5', '5,8', '1,8', '6,9', '1,10', '1,2', '4,7', '9,4']

I would like to sort it by first value of each element, but if two elements have the same value, then I would like to sort it by the original index. In this example I want ‘1,8’ to be before ‘1,10’ and ‘1,10’ before ‘1,2’, so the sorted list would look like this:

['1,8', '1,10', '1,2', '3,5', '4,7', '5,8', '6,9', '9,4']

How can I achieve this?

Solution

Python’s sort functions are stable, which means if the sort key is the same it will have the behavior you want. So you can just make a key that takes the first number ad ignores the rest. One way to pass the substring up to the "," and make it an integer:

l = ['3,5', '5,8', '1,8', '6,9', '1,10', '1,2', '4,7', '9,4']

sorted(l, key=lambda s: int(s[:s.index(',')]))
# ['1,8', '1,10', '1,2', '3,5', '4,7', '5,8', '6,9', '9,4']

Answered By – Mark

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published