在Python中使用多个NOT IN语句

时间:2016-07-01 17:42:28

标签: 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

谢谢!

1 个答案:

答案 0 :(得分:8)

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

来自docs

如果iterable的任何元素为true,则

any返回True。如果iterable为空,则返回False。相当于:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False