user3535074 user3535074 - 29 days ago 11
Python Question

Check string includes/does not include values from distinct lists

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)


I'm trying to achieve the following code but in a more pythonic way. Using generators I can manage to proceed based on a single list's items:

if any(dir in dirpath for dir in listIncludedFolders):
print(dirpath)


...but I can't add the second comparison. I managed in the below to have a single additional criteria but I need to iterate over a list of additional criteria:

if any(dir in dirpath for dir in listIncludedFolders if("Criteria2" not in dirpath)):
print(dirpath)


How can I achieve this 'cleanly'?

Answer

Combine two condition with and operator with another any call:

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

or with another and call (with condition negated):

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

BTW, (... for .. in .. if ..) is a generator expression, not a list comrpehension.