0

I have a simple question of sorting lists based on values. I want to order a list of strings as they are integers, and consider for sorting just the characters that are starting on second position.

As an example, I have this list:

L = ['X102', 'X201', 'X805', 'X111', 'X032', 'X155', 'X0123', 'X1113', 'X881', 'X1022']

if I sort it using sorted(L) I get:

['X0123', 'X032', 'X102', 'X1022', 'X111', 'X1113', 'X155', 'X201', 'X805', 'X881']

My struggle is to sort the list just considering the "integers", so just the numbers are after 'X' in order that the result to look like this:

SORTED_L = ['X032', 'X102', 'X111', 'X0123', 'X155', 'X201', 'X805', 'X881', 'X1022', 'X1113']
Ma0
  • 15,057
  • 4
  • 35
  • 65
alc
  • 199
  • 3
  • 15

1 Answers1

3

You can specify a custom sort key using a lambda function:

SORTED_L = sorted(L, key=lambda x: int(x.replace('X', ''))

In this case, for each value in L, the lambda will remove the 'X' and convert to an int.

pault
  • 41,343
  • 15
  • 107
  • 149