Using multiple NOT IN statements with Python

2020-04-05 08:35发布

I need to URLs with three specific specific substrings out of a loop. The following code worked, but I am sure there's a more elegant way to do it:

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

Thank you!

1条回答
够拽才男人
2楼-- · 2020-04-05 08:40
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

From the docs:

any returns True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
查看更多
登录 后发表回答