Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading