python - 在Python中对包含数字的字符串列表进行排序

标签 python string list sorting

所以我有一个字符串路径列表:

x = ['../../scene/temp_5a/458754/1_car.png',
     '../../scene/temp_5a/458754/2_car.png',
     '../../scene/temp_5a/458754/10_car.png',
     '../../scene/temp_5a/458754/15_car.png',
     '../../scene/temp_5a/458754/3_car.png']

我需要按_car前面的数字对其进行排序。有谁知道快速的方法吗?

我目前有这个,但似乎分割得到了所有数字。我只想获取_car前面的数字。

def atoi(text):
    return int(text) if text.isdigit() else text

def natural_keys(text):
    return [ atoi(c) for c in re.split('(\d+)', text) ]

x.sort(key=natural_keys) # gives an error

最佳答案

我不确定为什么你的正则表达式给你一个错误,它对我有用。也许尝试不同的正则表达式?

将您的替换为 r'.*\/([^_]*)_.*' 也可能有效:

x = ['../../scene/temp_5a/458754/1_car.png',
'../../scene/temp_5a/458754/2_car.png',
'../../scene/temp_5a/458754/10_car.png',
'../../scene/temp_5a/458754/15_car.png',
'../../scene/temp_5a/458754/3_car.png']

def atoi(text):
return int(text) if text.isdigit() else text

def natural_keys(text):
    return [ atoi(c) for c in re.split(r'.*\/([^_]*)_.*', text) ]

x.sort(key=natural_keys)
print x

输出:

['../../scene/temp_5a/458754/1_car.png',  
'../../scene/temp_5a/458754/2_car.png', 
'../../scene/temp_5a/458754/3_car.png', 
'../../scene/temp_5a/458754/10_car.png', 
'../../scene/temp_5a/458754/15_car.png']

关于python - 在Python中对包含数字的字符串列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43484731/

相关文章:

c# - 嵌套 LINQ 查询 - 列表中的列表

c# - 如何在一般的 c# 中将方法存储在堆栈或列表中

python - 如何在 Python 中打印 Unicode 字符代码?

python - 如何将图像数据从存储桶加载到AWS sagemaker笔记本?

python - 不要在管理页面中显示某些字段

java - 脏话测试未按预期工作(在聊天应用程序中)?

python - 如何将具有定义的共享子字符串的列表中的字符串移动到新列表?

python - 仅当模型在 TensorFlow 中显示改进时才保存模型检查点

c++ - 在只读场景中何时需要以空字符结尾的字符串?

java - 忽略字符串中的任何非字母字符和大写字母