python - 比较Python中两个列表的项目

标签 python

我阅读了很多关于相关问题的问题,但没有一个能回答我的问题。我有两个列表:

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 中找到它的所有希望:)

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

最佳答案

也许

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'

关于python - 比较Python中两个列表的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16295827/

相关文章:

python - Sonar Python 覆盖率报告问题

python - 使用 Pandas 计算简单的历史平均值

python - 分割不可散列类型的字符串

python - 图形学 : how to color nodes using values from a column

python - 如何使用 pysimplegui 在新行中打印列表的每个元素?

python - python 将一个数字与数字列表组成元组

python - 将 header 与 Python 请求库的 get 方法一起使用

python - 如何在 DataFrame 中有效更新一组行值?如何使这个算法具有可扩展性?

python - 加载pickled数据时cPickle EOFError

python - 添加新元素后,lxml 库不向树添加换行符或缩进