[英]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?
是正则表达式需要删除数字还是有更多的Pythonic方法来做到这一点?
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
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). key
是提取的数字(转换为int
以避免按字典顺序排序)。
If you don't want to use regex 如果你不想使用正则表达式
>>> 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(''.join(filter(str.isdigit, x))))
['1-bar', '2-bar', 'bar-3', 'foo-4', 'foobar-5', '6-foo', '7-bar', 'foo-11', '12-foo']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.