我需要将文件路径列表按字典顺序排序,例如输出
排序如下:C:TestProject1Exampletest1.txt
C:TestProject1Exampletest2.txt
C:TestProject1ExampleSubmeee.txt
C:TestProject1ExampleSubtest1.txt
C:TestProject1ExampleSubyouu.txt
C:TestProject1ExampleZzzzzz.py
当我自然地对其进行排序时,我在C:TestProject1Exampletest1.txt
之前收到C:TestProject1ExampleSubmeee.txt
并且不希望那样。
您可以将sorted
与自定义键一起使用,该键为根目录中的文件提供优先级:
L = [r'C:TestProject1Exampletest1.txt', r'C:TestProject1Exampletest2.txt',
r'C:TestProject1ExampleSubmeee.txt', r'C:TestProject1ExampleSubtest1.txt',
r'C:TestProject1ExampleSubyouu.txt', r'C:TestProject1ExampleZzzzzz.py']
def sort_key(x):
splits = x.split('\')[4:]
return len(splits), splits
res = sorted(L, key=sort_key)
['C:\Test\Project1\Example\test1.txt',
'C:\Test\Project1\Example\test2.txt',
'C:\Test\Project1\Example\Sub\meee.txt',
'C:\Test\Project1\Example\Sub\test1.txt',
'C:\Test\Project1\Example\Sub\youu.txt',
'C:\Test\Project1\Example\Zzz\zzz.py']