1

我阅读了许多有关相关问题的问题,但没有一个回答我的问题。我有两个清单:

List A = ['nike', 'adidas', 'reebok']

List B = ['sneakers', 'sneaker shoes', 'adidas shoes', 'nike', 'any shoe', 'all nikes', 'a nike shoe']

现在,我想查看列表 A 的项目是否存在于 B 中的某个位置,以便它返回:

List result: [False, False, True, True, False, True, True]

True 表示列表 B 中匹配 A 项的实例。到目前为止,我使用的代码似乎非常低效。

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')

提前感谢,如果确实有答案,我很抱歉 - 一个小时后,我失去了在 stackoverflow-universe 中找到它的所有希望 :)

编辑:很抱歉没有让自己清楚 - 我不是在寻找完全匹配,我在寻找短语匹配。再次抱歉!

4

1 回答 1

5

也许

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]

或更好

import re
regex = re.compile(r'%s' % '|'.join(keywords))
bits = [bool(regex.search(x)) for x in items]

据我了解,您想忽略单词边界(例如“nike”匹配“all nikes”),仅搜索完整单词,将上述表达式更改为r'\b(%s)\b'.

于 2013-04-30T08:58:29.490 回答