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']