Home > Mobile >  Sort strings of ints and save original index
Sort strings of ints and save original index

Time:09-04

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:

[(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.

CodePudding user response:

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