I would like to know how can I sort a string by the number inside.
As example I have:
hello = " hola %d" % (number_from_database)
bye = "adios %d" % (number_from_database_again)
I want to sort them by the number even if it changes.
您可以传递一个键进行排序:
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']
Wherere.sub('\D', '', x)
替换了除数字之外的所有内容。
只是对安迪的回答的一点补充。
如果要对还包含没有任何数字的字符串的集合进行排序:
sorted(l, key=lambda x: int('0'+re.sub('\D', '', x)))
,这会将那些没有任何数字的字符串放在开头。
salutations = [hello, bye]
salutations.sort(key=lambda x: int(filter(lambda s: s.isdigit(), x.split())[0]))