按数字对字符串进行排序 [英] sort string by number inside
本文介绍了按数字对字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何根据内部数字对字符串进行排序.
I would like to know how can I sort a string by the number inside.
例如,我有:
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.
推荐答案
您可以传递密钥进行排序:
You can pass a key to sort:
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)
替换除数字外的所有字符.
这篇关于按数字对字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文