我有文件名的形式列表:数控订购基于图案列表
['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt']
我不知道如何将这个列表数值排序,以获得输出:
['comm_1_1.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt', 'comm_1_10.txt', 'comm_1_11.txt']
我有文件名的形式列表:数控订购基于图案列表
['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt']
我不知道如何将这个列表数值排序,以获得输出:
['comm_1_1.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt', 'comm_1_10.txt', 'comm_1_11.txt']
你应该分裂所需号码,并将其转换为int
ss = ['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt']
def numeric(i):
return tuple(map(int, i.replace('.txt', '').split('_')[1:]))
sorted(ss, key=numeric)
# ['comm_1_1.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt', 'comm_1_10.txt', 'comm_1_11.txt']
我真的不认为这是一个最好的答案,但你可以 试试看。用于这种“人排序”的
l = ['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt']
d = {}
for i in l:
filen = i.split('.')
key = filen[0].split('_')
d[int(key[2])] = i
for key in sorted(d):
print(d[key])
的一种技术是键分裂到元组和转换数字部分实际数字:
ss = ['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt']
print(sorted(ss, key=lambda x : map((lambda v: int(v) if "0" <= v[0] <= "9" else v), re.findall("[0-9]+|[^0-9]+", x))))
,或者更可读
def sortval(x):
if "0" <= x <= "9":
return int(x)
else:
return x
def human_sort_key(x):
return map(sortval, re.findall("[0-9]+|[^0-9]+", x))
print sorted(ss, key=human_sort_key)
该想法是将数字部分和非数字部分分开,并在将数字部分转换为实际数字后将这些部分放入列表中(以便10
在之后)。
按字母顺序排列列表给出了预期的结果。