-1

I would like to sort strings by numbers, but keep them in groups. Means, keep Cs, Rs, ... together, but in a numeric sorted order. There are similar questions like here Is there a built in function for string natural sort?, but all of them are dealing with strings starting with the same string. So this is little bit different.


# input
a = ['C2', 'C1', 'R3', 'R21', 'C10', 'R1', 'L1']
# expected output
['C1', 'C2', 'C10', 'R1', 'R3', 'R21', 'L1']

# I tried multiple options, but didn't find the right one.
a.sort(key=lambda x: int(x[1:]))

So how to get the results without creating the special parsing function?

Thanks

Andy
  • 74
  • 9

1 Answers1

1

You can use a tuple of the letter and number instead of just the number in sort:

>>> a.sort(key=lambda x: (x[0], int(x[1:])))
['C1', 'C2', 'C10', 'L1', 'R1', 'R3', 'R21']
asdf101
  • 569
  • 5
  • 18
  • FYI, you dont need to convert `x[1:]` to an int, but otherwise I was going to say the same thing – Tom McLean Feb 05 '23 at 16:10
  • 2
    @TomMcLean correct, but if for some reason the second element of a string should always be a number it shouldn't fail silently imho – asdf101 Feb 05 '23 at 16:16