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

2024-09-23 06:37:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

我怎样才能做到“干净”?你知道吗


Tags: infalsetrue列表forifdirany
3条回答

这非常有效:

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)

您可以避免进入被排除在第一位的子树。这个解决方案也比原来的方法更健壮,假设测试子字符串以确定文件夹的包含和排除不是什么意思(您真的要排除名为“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在排除列表中,那么在这个实现中它将被忽略。你知道吗

将带有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。你知道吗

相关问题 更多 >