在Python中使用多个NOT IN语句

tno*_*sky 4 python if-statement conditional-statements

我需要一个循环中带有三个特定特定子串的URL.以下代码有效,但我确信有一种更优雅的方式:

for node in soup.findAll('loc'):
    url = node.text.encode("utf-8")
    if "/store/" not in url and "/cell-phones/" not in url and "/accessories/" not in url:
        objlist.loc.append(url) 
    else:
        continue
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ian*_*ice 7

url = node.text.encode("utf-8")    
sub_strings = ['/store','/cell-phones/','accessories']

if not any(x in url for x in sub_strings):
    objlist.loc.append(url)
else:
    continue
Run Code Online (Sandbox Code Playgroud)

来自文档:

any如果iterable的任何元素为true,则返回True.如果iterable为空,则返回False.相当于:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
Run Code Online (Sandbox Code Playgroud)

  • 您也可以不应用de Morgan变换并执行`all(x不是在sub_strings中的x的url). (2认同)