khm*_*khm 2 python sorting python-3.4
好的,所以我需要做的是对 python 3.4 中的文件路径列表进行排序。它们需要按字母顺序排列,但子文件夹及其内容排在第一位
示例输出:
b/e/f.txt
b/d.txt
g/u.txt
i/a/q.txt
a.txt
c.txt
d.txt
Run Code Online (Sandbox Code Playgroud)
在过去的几个小时里,我一直试图通过 Google 找出如何做到这一点,但没有运气
恐怕我目前无法访问 v2 解释器,所以我无法验证其正确性,但在 v2 中它看起来像这样:
def FileComp(File1, File2):
if File1.count('/') == File2.count('/'):
return File1 < File2;
else
Same = 0;
FilePath1 = os.path.dirname(File1);
FilePath2 = os.path.dirname(File2);
FilePath1Len = len(FilePath1);
FilePath2Len = len(FilePath2);
while Same < FilePath1Len and Same < FilePath2Len and FilePath1[Same:Same] == FilePath2[Same:Same]:
Same += 1;
FilePath1 = FilePath1[Same:];
FilePath2 = FilePath2[Same:];
if len(FilePath1) == 0 or len(FilePath2) == 0:
return len(FilePath1) > len(FilePath2);
else
return File1 < File2;
Files.sort(FileComp);
Run Code Online (Sandbox Code Playgroud)
如果您需要先对子文件夹进行排序,则需要提供两件事进行排序:如果它不是子文件夹(True在之后排序False),则需要提供一个标志,以及路径本身:
sorted(paths, key=lambda p: (os.path.sep not in p, p))
Run Code Online (Sandbox Code Playgroud)
这用于os.path.sep确定路径是否用于子文件夹,因此您首先获取子文件夹。
So'a.txt'变换为(True, 'a.txt'), while'b/d.txt'排序为(False, 'b/d.txt'); 元组按字典顺序排序,并False在 before 之前排序True。
如果您需要将较深的文件夹排序在较浅的文件夹之前,请计算分隔符的数量并将其返回为负值;斜杠越多,文件夹越“深”,它将被排序在其他文件夹之前:
sorted(paths, key=lambda p: (-p.count(os.path.sep), p))
Run Code Online (Sandbox Code Playgroud)
演示:
>>> import os.path
>>> paths = '''\
... b/e/f.txt
... b/d.txt
... a.txt
... c.txt
... '''.splitlines()
>>> sorted(paths, key=lambda p: (os.path.sep not in p, p))
['b/d.txt', 'b/e/f.txt', 'a.txt', 'c.txt']
>>> import random
>>> random.shuffle(paths)
>>> sorted(paths, key=lambda p: (os.path.sep not in p, p))
['b/d.txt', 'b/e/f.txt', 'a.txt', 'c.txt']
>>> sorted(paths, key=lambda p: (-p.count(os.path.sep), p))
['b/e/f.txt', 'b/d.txt', 'a.txt', 'c.txt']
Run Code Online (Sandbox Code Playgroud)