在Python中使用多个NOT IN语句 [英] Using multiple NOT IN statements with Python

查看:1635
本文介绍了在Python中使用多个NOT IN语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在循环中包含三个特定特定子字符串的URL。以下代码有效,但我确信有更优雅的方法:

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

谢谢!

推荐答案

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,则返回True。如果iterable为空,则返回False。相当于:

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

这篇关于在Python中使用多个NOT IN语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆