呼如林
数据是按字母排序的,如果你要实现13_left.jpg, 14_left.jpg.....13_right.jpg, 14_right.jpg这样的顺序,就得写个排序方法做排序。import os
def compare(x, y):
xparts = x.split('_')
yparts = y.split('_')
if len(xparts) > 1 and len(yparts) > 1:
if xparts[1] == yparts[1]:
try:
return cmp(int(xparts[0]),int(yparts[0]))
except:
pass
return cmp(xparts[0], yparts[0])
else:
return cmp(xparts[1], yparts[1])
else:
return cmp(x, y)
items = os.listdir('./tmp')
print items
items.sort(compare)
print items输出:['10_right.jpg', '11_right.jpg', '1_left.jpg', '1_right.jpg', '20_left.jpg', '2_left.jpg', '2_right.jpg']['1_left.jpg', '2_left.jpg', '20_left.jpg', '1_right.jpg', '2_right.jpg', '10_right.jpg', '11_right.jpg']