我刚刚开始编写Python编程,希望一些经验丰富的人可以给我
有关如何优化以下代码的提示.
我想要做的是浏览文件夹列表,使新列表仅包含每组文件夹中的顶级文件夹.
我一直在努力并编写下面的代码来完成工作,但是当使用包含数千个文件夹的列表时,伸缩性会非常差.
欢迎任何喜欢如何优化此例程的想法.
folderlist = [ "c:\\temp\\data\\1122 AA",\
"c:\\temp\\data\\1122 AA\\Div",\
"c:\\temp\\data\\1122 AA\\Div\\Etc",\
"c:\\temp\\data\\1122 AA\\Div\\Etc2",\
"c:\\temp\\server1\\div\\2244_BB",\
"c:\\temp\\server1\\div\\2244_BB\\pp",\
"c:\\temp\\server1\\div\\2244_BB\\der\\dedd",\
"c:\\temp\\server1\\div\\2244_BB\\defwe23d\\23ded",\
"c:\\temp\\123456789-BB",\
"c:\\temp\\123456789-BB\\pp",\
"c:\\temp\\123456789-BB\\der\\dee32d",\
"c:\\temp\\data\\123456789-BB\\ded\\ve_23"]
l2 = folderlist.copy()
ind = []
indexes_to_be_deleted = []
for el in l2:
for idx,x in enumerate(l2):
if el in x:
ind.append(idx)
counts = Counter(ind)
for l,count in counts.most_common():
if count > 1:
indexes_to_be_deleted.append(l)
for i in sorted(indexes_to_be_deleted,reverse=True):
del folderlist[i]
Output:
c:\\temp\\data\\1122 AA\\
c:\\temp\\server1\\div\\2244_BB\\
c:\\temp\\123456789-BB\\
最佳答案