[英]Comparing the items of two lists in Python
I read numerous questions on related issues, but none of them answers my question. 我阅读了许多有关相关问题的问题,但没有一个回答我的问题。 I have two lists:
我有两个清单:
List A = ['nike', 'adidas', 'reebok']
List B = ['sneakers', 'sneaker shoes', 'adidas shoes', 'nike', 'any shoe', 'all nikes', 'a nike shoe']
Now, I want to see if the items of List A exist somewhere in B, so that it returns: 现在,我想看看列表A的项目是否存在于B的某处,以便返回:
List result: [False, False, True, True, False, True, True]
True represents the instance in List B where an item of A is matched. True表示列表B中与A项匹配的实例。 So far, I have used this code which seems terribly inefficient.
到目前为止,我已经使用了这段效率极低的代码。
for j in range(len(lista)):
for k in b:
if j in k:
lista[j] = 'DELETE'
cuent = lista.count('DELETE')
for i in range(cuent):
lista.remove('DELETE')
Thanks in advance and sorry if there is indeed an answer to this - after an hour I have lost all hope of finding it in the stackoverflow-universe :) 在此先感谢,如果确实有答案,对不起-一个小时后,我失去了在stackoverflow-universe中找到它的所有希望:)
EDIT: Sorry for not making myself clear - I am NOT looking for exact matches, I am looking for phrase matches. 编辑:对不起,我自己说不清楚-我不是在寻找完全匹配的内容,我正在寻找词组匹配的内容。 Sorry again!
再次抱歉!
Maybe 也许
keywords = ['nike', 'adidas', 'reebok']
items = ['sneakers', 'sneaker shoes', 'adidas shoes', 'nike', 'any shoe', 'all nikes', 'a nike shoe']
bits = [any(keyword in item for keyword in keywords) for item in items]
or better 或更好
import re
regex = re.compile(r'%s' % '|'.join(keywords))
bits = [bool(regex.search(x)) for x in items]
From my understanding, you want to ignore word boundaries (eg "nike" matches "all nikes"), to search full words only, change the above expression to r'\\b(%s)\\b'
. 据我了解,您想忽略单词边界(例如,“ nike”匹配“ all nikes”),仅搜索完整单词,将上述表达式更改为
r'\\b(%s)\\b'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.