我有一个字符串列表,现在想要按照每个元素中的数字进行排序。使用sorted
失败了,因为它无法处理像10
和3
之间的顺序。我可以想象如果我使用re
,就可以解决这个问题。但是这样不够有趣。你们有什么好的实现想法吗?我假设这段代码是用Python 3.x编写的。
names = [
'Test-1.model',
'Test-4.model',
'Test-6.model',
'Test-8.model',
'Test-10.model',
'Test-20.model'
]
number_sorted = get_number_sorted(names)
print(number_sorted)
'Test-20.model'
'Test-10.model'
'Test-8.model'
'Test-6.model'
'Test-4.model'
'Test-1.model'
x.removeprefix('Test-').removesuffix('.model')
可能比.replace
版本更合适。str.removeprefix和str.removesuffix的文档 - Stef