【发布时间】:2017-09-15 00:48:56
【问题描述】:
所以我有一个字符串路径列表:
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
【问题讨论】:
-
最后一行给你的错误是什么?我运行了你的代码,得到了你想要的排序输出,没有错误。
-
你是对的!我忘记了 x.sort() 对数组进行排序,所以它输出 None 并导致我的部分代码吐出垃圾。谢谢!
-
啊,是的,我知道那种感觉!很高兴听到你想通了,很高兴能提供帮助。干杯!
标签: python string list sorting