adele adele - 3 months ago 12
Python Question

Sort list of mixed strings based on digits

How do I sort this list via the numerical values? Is a regex required to remove the numbers or is there a more Pythonic way to do this?

to_sort

['12-foo',
'1-bar',
'2-bar',
'foo-11',
'bar-3',
'foo-4',
'foobar-5',
'6-foo',
'7-bar']


Desired output is as follows:

1-bar
2-bar
bar-3
foo-4
foobar-5
6-foo
7-bar
foo-11
12-foo

Answer

One solution is the following regex extraction:

sorted(l, key=lambda x: int(re.search('\d+', x).group(0)))

>>> l
['12-foo', '1-bar', '2-bar', 'foo-11', 'bar-3', 'foo-4', 'foobar-5', '6-foo', '7-bar']
>>> sorted(l, key=lambda x: int(re.search('\d+', x).group(0)))
['1-bar', '2-bar', 'bar-3', 'foo-4', 'foobar-5', '6-foo', '7-bar', 'foo-11', '12-foo']

The key is the extracted digit (converted to int to avoid sorting lexographically).