如何按字母数字顺序设置列表?

时间:2017-10-04 08:33:02

标签: python list sorting

我有一个包含10个子文件夹的文件夹,其中包含以下命名:

Folder1中,FOLDER2,Folder3,... 我想按照那个顺序操纵它们但是当我申请时

lst = os.listdir(dirname)
lst.sort()

输出如下:

Folder1
Folder10
Folder2
Folder3
Folder4
Folder5
Folder6
Folder7
Folder8
Folder9

这是预期的,为了正确排序我做了以下事情:

lst = os.listdir(dirname)
lst.sort()

projects = {}

for p in lst:
    pInt = re.sub(r"Folder", " ", p)
    projects[pInt] = p
    print(p)

print projects

获得以下结果:

{' 10': 'Folder10', ' 2': 'Folder2', ' 3': 'Folder3', ' 1': 'Folder1', ' 6': 'Folder6', ' 7': 'Folder7', ' 4': 'Folder4', ' 5': 'Folder5', ' 8': 'Folder8', ' 9': 'Folder9'}

我如何从那里开始正确列出它们,以便我的系统将按顺序逐个访问它们

1 个答案:

答案 0 :(得分:2)

您可以将sorted与自定义密钥一起使用。默认值是词典顺序,不适用于您的目的。

>>> data
['Folder1', 'Folder10', 'Folder2', 'Folder3', 'Folder4', 'Folder5', 'Folder6', 'Folder7', 'Folder8', 'Folder9']
>>> sorted(data)
['Folder1', 'Folder10', 'Folder2', 'Folder3', 'Folder4', 'Folder5', 'Folder6', 'Folder7', 'Folder8', 'Folder9']
>>> sorted(data, key= lambda s: int(s.replace('Folder', '')))
['Folder1', 'Folder2', 'Folder3', 'Folder4', 'Folder5', 'Folder6', 'Folder7', 'Folder8', 'Folder9', 'Folder10']

如果不是每个文件夹都被称为FolderX,您可以使用此密钥:

>>> sorted(data, key= lambda s: int(''.join(filter(str.isdigit, s))))
['Folder1', 'Folder2', 'Data3', 'Folder4', 'Folder5', 'Folder6', 'Folder7', 'Folder8', 'Folder9', 'Folder10']

另一种方法是将folderX重命名为folder0X。然后会在Folder02之前对Folder10进行排序。