1

Here is my input:

a = ['Dr1', 'Dr10', 'Dr11', 'Dr12','Dr2', 'Dr3']
a.sort()
print(a)

Here is the current output:

['Dr1', 'Dr10', 'Dr11', 'Dr12', 'Dr2', 'Dr3']

Here is the output I would like generated instead:

['Dr1', 'Dr2', 'Dr3', 'Dr10', 'Dr11', 'Dr12']
Greg
  • 168
  • 1
  • 3
  • 19
  • 1
    Are your strings always of the form `Dr` followed by a number? If so, you can just sort by `key=lambda x: int(x[2:])`, or the other things shown in the answers to the linked duplicate. But if the letters can be different, and you want to consider them—so, e.g., `Dr2` comes before `Dr10`, but `Mr1` comes after `Dr2`, you probably want a "natural sort" library rather than building it by hand. – abarnert Aug 19 '18 at 00:39

1 Answers1

0

In order to sort via the trailing value in each element, use re:

import re
a = ['Dr1', 'Dr10', 'Dr11', 'Dr12','Dr2', 'Dr3']
new_a = sorted(a, key=lambda x:int(re.findall('\d+', x)[0]))

Output:

['Dr1', 'Dr2', 'Dr3', 'Dr10', 'Dr11', 'Dr12']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102