我需要在循环中包含三个特定特定子字符串的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
谢谢!
答案 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