我有以下字符串列表。然后,我想按每个元素中的数字对其进行排序。 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'
最佳答案
关键是……关键
sorted(names, key=lambda x: int(x.partition('-')[2].partition('.')[0]))
通过将字符串的那部分分离出来并将其转换为 int,将其识别为排序顺序。
关于python - 按字符串中的数字对字符串列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48413706/