检查字符串包含/不包含不同列表中的值

时间:2016-11-09 11:18:49

标签: python list python-3.x generator os.walk

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)

我正在尝试以更加pythonic的方式实现以下代码。使用生成器我可以设法根据单个列表的项目继续:

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)

我怎样才能“干净利落地”实现这个目标?

3 个答案:

答案 0 :(得分:2)

and运算符与另一个any调用符合并:

if any(each in dirpath for each in listIncludedFolders) and \
        not any(each in dirpath for each in listExcludedFolders):
    print(dirpath)

或另一个and调用(条件被否定):

if any(each in dirpath for each in listIncludedFolders) and \
       all(each not in dirpath for each in listExcludedFolders):
    print(dirpath)

顺便说一句,(... for .. in .. if ..)generator expression,而不是list comrpehension

答案 1 :(得分:1)

您可以避免进入首先排除的子树。此解决方案也比原始方法更强大,假设测试子字符串以确定包含和排除文件夹不是意味着什么(你真的想要排除名为&#34的文件夹; Criteria2345"?)

for dirpath, dirnames, filenames in os.walk(root):
    if set(dirpath.split(os.path.sep)) & set(listIncludedFolders):
        print(dirpath)
    for ex in [dnam for dnam in dirnames if dnam in listExcludedFolders]:
        dirnames.remove(ex)

但请注意,如果root位于排除列表中,则在此实现中将忽略它。

答案 2 :(得分:0)

这完美无缺:

listIncludedFolders = ["Criteria1"]
listExcludedFolders = ["Criteria2"]

for dirpath, dirnames, filenames in os.walk(root):

    if any(each in dirpath for each in listIncludedFolders) and \
            not any(each in dirpath for each in listExcludedFolders):
        print(dirpath)