[英]checking if any of multiple substrings is contained in a string - Python
我有一个包含禁止子字符串的黑名单:我需要创建一个 if 语句来检查给定 url 中是否包含任何被禁止的子字符串。 如果它不包含其中任何一个,我希望它执行 A(如果存在任何被禁止的内容,则只执行一次,而不是针对每个被禁止的子字符串)。 如果 url 包含一个被禁止的子字符串,我希望它做 B。
black_list = ['linkedin.com', 'yellowpages.com', 'facebook.com', 'bizapedia.com', 'manta.com',
'yelp.com', 'nextdoor.com', 'industrynet.com', 'twitter.com', 'zoominfo.com',
'google.com', 'yellow-listings.com', 'kompass.com', 'dnb.com', 'tripadvisor.com']
这里只是我用来检查它是否有效的两个简单的 url 示例。 Url1 已禁止 substring 内部,而 url2 没有。
url1 = 'https://www.dnb.com/'
url2 = 'https://www.ok/'
我尝试了下面的代码,但是如果有更好的方法(计算效率更高),我会徘徊吗? 我有一个 100k+ url 的数据框,所以担心这会超级慢。
mask = []
for banned in black_list:
if banned in url:
mask.append(True)
else:
mask.append(False)
if any(mask):
print("there is a banned substring inside")
else:
print("no banned substrings inside")
有人知道更有效的方法吗?
这是一个可能的单行解决方案:
print('there is a banned substring inside'
if any(banned_str in url for banned_str in black_list)
else 'no banned substrings inside')
如果您更喜欢不那么 Pythonic 的方法:
if any(banned_str in url for banned_str in black_list):
print('there is a banned substring inside')
else:
print('no banned substrings inside')
您应该根据执行A
或B
添加一个标志。
ban_flag = False
for banned in black_list:
if banned not in url:
continue
else:
ban_flag = True
if ban_flag:
print("there is a banned substring inside")
else:
print("no banned substrings inside")
代码:
black_list = ['linkedin.com', 'yellowpages.com', 'facebook.com', 'bizapedia.com', 'manta.com',
'yelp.com', 'nextdoor.com', 'industrynet.com', 'twitter.com', 'zoominfo.com',
'google.com', 'yellow-listings.com', 'kompass.com', 'dnb.com', 'tripadvisor.com']
def is_url_banned(url):
for banned in black_list:
if banned in url :
print("there is a banned substring inside")
return
print("no banned substrings inside")
is_url_banned('https://www.dnb.com/')
is_url_banned('https://www.ok/')
结果:
there is a banned substring inside
no banned substrings inside
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.