gpt4 book ai didi

python - 检查字符串包括/不包括来自不同列表的值

转载 作者:太空宇宙 更新时间:2023-11-04 00:44:13 24 4
gpt4 key购买 nike

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)

我怎样才能“干净利落地”实现这一点?

最佳答案

将两个条件与 and 运算符与另一个 any 调用结合起来:

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

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

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 .

关于python - 检查字符串包括/不包括来自不同列表的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com