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

Time:01-09

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?

CodePudding user response:

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']
  •  Tags:  
  • Related