首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >if python语句中有多个and

if python语句中有多个and
EN

Stack Overflow用户
提问于 2020-05-15 13:21:12
回答 3查看 63关注 0票数 0

我正在编写一个python爬虫程序,它可以在给定页面的urls中找到联系人链接。然而,我的if语句看起来很糟糕:

代码语言:javascript
复制
if 'news' not in link and 'archive' not in link and 'download' not in link and 'career' not in link and '././' not in link and '..' not in link and '../' not in link and 'store' not in link and 'mailto' not in link and 'tel:' not in link and '.pdf' not in link:

必须有更好的方法来做到这一点。尤其是因为当我浏览越来越多的站点时,我会添加更多关于url可以包含什么的规则。

请帮帮我!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-05-15 13:27:45

使用all

代码语言:javascript
复制
excluded = ['news', 'archive', ]

if all(part not in link for part in excluded):

any

代码语言:javascript
复制
if not any(part in link for part in excluded):
票数 4
EN

Stack Overflow用户

发布于 2020-05-15 13:28:41

您可以聪明地使用all和列表理解

代码语言:javascript
复制
checks = ['foo', 'bar']

link = ['something']

if all(k not in link for k in checks):
   #do something

如果给定列表中的所有项都为True,则all返回True

如果给定列表中的任何项为True,则any返回True

示例:

代码语言:javascript
复制
>>> l0 = [False, False]
>>> any(l0)
False
>>> all(l0)
False
>>> l1 = [True, False]
>>> any(l1)
True
>>> all(l1)
False
>>> l2 = [True, True]
>>> any(l2)
True
>>> all(l2)
True
票数 1
EN

Stack Overflow用户

发布于 2020-05-15 13:40:30

您可以使用列表来存储匹配模式,而不是在单个条件中检查所有匹配模式。例如。

代码语言:javascript
复制
link = 'https://example.com/news'
matchings = ['news', 'archive', 'etc']
for match in matchings:
    if not match in link:
        do_something()
        break
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61812278

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档