【问题标题】:Using multiple NOT IN statements with Python在 Python 中使用多个 NOT IN 语句
【发布时间】:2016-11-04 04:59:03
【问题描述】:

我需要从一个循环中取出带有三个特定子字符串的 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

谢谢!

【问题讨论】:

  • 可以全部使用内置函数

标签: python if-statement conditional-statements


【解决方案1】:
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

any 如果可迭代的任何元素为真,则返回真。如果可迭代对象为空,则返回 False。相当于:

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

【讨论】:

  • 轰隆隆。谢谢,伊恩!
  • 你也不能应用德摩根转换并做all(x not in url for x in sub_strings)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多