我想知道如何按内部数字排序字符串。
例如,我有以下字符串:
hello = " hola %d" % (number_from_database)
bye = "adios %d" % (number_from_database_again)
我希望按照数字大小对它们进行排序,即使数字发生改变也要排序。
您可以传递一个键来进行排序:
sorted(l, key=lambda x: int(re.sub('\D', '', x)))
例如:
In [1]: import re
In [2]: l = ['asdas2', 'asdas1', 'asds3ssd']
In [3]: sorted(l, key=lambda x: int(re.sub('\D', '', x)))
Out[3]: ['asdas1', 'asdas2', 'asds3ssd']
re.sub('\D', '', x)
替换除了数字以外的所有内容。
这是对安迪答案的补充。
如果您想排序包含字符串但没有任何数字的集合:
sorted(l, key=lambda x: int('0'+re.sub('\D', '', x)))
这将把那些没有任何数字的字符串放在最前面。
上述解决方案对于具有以下格式的字符串无效:
test 8 - test 18
818
而不是8
:x = 'test 8 - test 18'
res = int(re.sub(r'\D', '', x))
print(res)
>>> 818
解决方法是执行搜索
并获取组
结果:
x = 'test 8 - test 18'
res = int(re.search(r'\d+', x).group())
print(res)
>>> 8
所以,带有这个更正的最终解决方案是:
l = [
'test 9 - test 8',
'test 8 - test 18'
]
l2 = sorted(l, key=lambda x: int(re.search(r'\d+', x).group()))
print(l)
print(l2)
>>> ['test 9 - test 8', 'test 8 - test 18']
['test 8 - test 18', 'test 9 - test 8']
salutations = [hello, bye]
salutations.sort(key=lambda x: int(filter(lambda s: s.isdigit(), x.split())[0]))
hello
和bye
。 - Martijn Pieters