python - 按字符串中的数字对字符串列表进行排序?

标签 python python-3.x string sorting

我有以下字符串列表。然后,我想按每个元素中的数字对其进行排序。 sorted 失败,因为它无法处理 103 之间的顺序。我可以想象如果我使用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/

相关文章:

python - 这两行如何工作 x2 = x+delta[i][0] , y2 = y+delta[i][1]?

python - matplotlib 内联facecolor 不适用于savefig

python - 如何在Python 3.6中提高SQLite插入性能?

c++ - C++字符串程序引起的运行时错误

linux - 在 Bash 中按照特定模式生成随机字符串的最佳方法

c - 在 C 中使用 strcpy() 和复制 char* 的地址之间的区别

python - U-SQL Python 扩展 DataFrame 列格式

python - 用户选择的变量从列表中删除

sqlite - 使用Python3和sqlite3和复杂的unicode字符串

python - 按内部数组的特定元素分组