【问题标题】:Comparing the items of two lists in Python在 Python 中比较两个列表的项目
【发布时间】:2013-04-30 08:53:05
【问题描述】:

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

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

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

【问题讨论】:

    标签: python


    【解决方案1】:

    也许

    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'

    【讨论】:

    • 这太完美了——我还不熟悉很短的“(keyword in item for keyword in keywords)”——表达式——你知道我在哪里可以了解更多吗?谢谢!
    • @oliver13:这被称为“生成器表达式”。参见例如stackoverflow.com/q/1756096/989121 解释。
    • @Haidro:这不是列表理解。
    • 哦,我以为他在说for x in y的语法。那是我的错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多