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

Sort strings of ints and save original index

I would like to sort lists of the following form:

['1000-1005', '6767-8787', '88-5607', '600-607', '909-950']

by the integer value before the ‘-‘ symbol and also store the original index after sorting, so something like 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

[(2, '88-5607'), (3, '600-607'), (4, '909-950'), (0, '1000-1005'), (1, '6767-8787')]

Where the tuples in the output list contain the original index position followed by the sorted value

Is there an easy way to do this?

If I want to sort by the first number without saving original indices, this works:

sorted(list, key=lambda x: int(x.split('-')[0]))

and if I want to save the original indices after extracting the first integer value, this works:

sorted(enumerate(list), key=lambda i: i[1])

but combining the approaches doesn’t work since they both eat up the key function definition.

>Solution :

Try:

res = sorted(enumerate(['1000-1005', '6767-8787', '88-5607', '600-607', '909-950']), 
             key=lambda x: int(x[1].split('-')[0]))
print(res)

Prints:

[(2, '88-5607'), (3, '600-607'), (4, '909-950'), (0, '1000-1005'), (1, '6767-8787')]
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