所以我有一个字符串路径列表:
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/