[英]How to check if part of one list is in another list
Suppose I have two lists like:假设我有两个列表,例如:
list_of_urls = ['https://en.wikipedia.org/wiki/Barack_Obama', 'https://en.wikipedia.org/wiki/President_of_the_United_States', 'google.com']
list_of_blacklisted_urls = ['wikipedia']
How to return True
if any part of the blacklisted url is in the list_of_urls?如果列入黑名单的 url 的任何部分在 list_of_urls 中,如何返回True
? I have tried:我试过了:
for url in list_of_urls:
if any(URL in URLs for URL in list_of_blacklisted_urls):
return True
But I'm quite sure this doesn't work.但我很确定这行不通。
You're pretty close... But the any
function doesn't work the way you seem to think it does.你很接近......但是any
函数并没有像你认为的那样工作。 You have to use a nested loop instead.您必须改用嵌套循环。
Here's an example:下面是一个例子:
list_of_urls = ['https://en.wikipedia.org/wiki/Barack_Obama', 'https://en.wikipedia.org/wiki/President_of_the_United_States', 'google.com']
list_of_blacklisted_urls = ['wikipedia']
for url in list_of_urls:
for keyword in list_of_blacklisted_urls:
if keyword in url:
print("FOUND", keyword, "in", url)
data = pd.DataFrame(list_of_urls)
data = data[data[0].str.contains(*list_of_blacklisted_urls)]
then you can see the result checking data.然后你可以看到结果检查数据。
How about this:这个怎么样:
def in_black_urls():
for black_url in list_of_blacklisted_urls :
if black_url in list_of_urls:
return True
return False
只需一行,保持简单:
len([x for x in list_of_urls if any(y in x for y in list_of_blacklisted_urls)]) > 0
You can use nested loop and 'in':您可以使用嵌套循环和 'in':
list_of_urls = ['https://en.wikipedia.org/wiki/Barack_Obama', 'https://en.wikipedia.org/wiki/President_of_the_United_States', 'google.com']
list_of_blacklisted_urls = ['wikipedia']
def checker(urls,blacklist):
for url in urls:
for URL in blacklist:
if URL in url:
print(True, url, URL)
else:
return False
checker(list_of_urls,list_of_blacklisted_urls)
Using nested list comprehension:使用嵌套列表理解:
def blacklisted(all_urls, blacklist):
if len([word for url in all_urls for word in blacklist if word in url]) > 0:
return True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.