listIncludedFolders = ["Criteria1"]
listExcludedFolders = ["Criteria2"]
for dirpath, dirnames, filenames in os.walk(root):
proceed = False
for each in listIncludedFolders:
if each in dirpath:
proceed = True
if proceed == True:
for each in listExcludedFolders:
if each in dirpath:
proceed = False
if proceed == True:
print(dirpath)
我试图实现以下代码,但在一个更python的方式。使用生成器,我可以根据单个列表的项继续:
if any(dir in dirpath for dir in listIncludedFolders):
print(dirpath)
…但我不能再加上第二个比较。我设法在下面有一个单独的附加条件,但我需要遍历一个附加条件列表:
if any(dir in dirpath for dir in listIncludedFolders if("Criteria2" not in dirpath)):
print(dirpath)
我怎样才能做到“干净”?你知道吗
这非常有效:
您可以避免进入被排除在第一位的子树。这个解决方案也比原来的方法更健壮,假设测试子字符串以确定文件夹的包含和排除不是什么意思(您真的要排除名为“Criteria2345”的文件夹吗?)你知道吗
但是请注意,如果
root
在排除列表中,那么在这个实现中它将被忽略。你知道吗将带有
and
运算符的两个条件与另一个any
调用组合:或者使用另一个
and
调用(条件为否定):顺便说一句,
(... for .. in .. if ..)
是generator expression,不是list comrpehension。你知道吗相关问题 更多 >
编程相关推荐