【问题标题】:how do i filter a list with another list in python我如何在python中用另一个列表过滤一个列表
【发布时间】:2018-06-03 10:13:59
【问题描述】:

我对 python 很陌生,基本上我需要过滤并获取 listA 中存在于 listB 中的所有项目。

listA = ['cat','dog','cow']

listB = ['sentence 1','sentence 2 contains cat','sentence 3',
         'sentence 4','sentence 5','sentence 6 contains dog']

result = ['sentence 2 contains cat','sentence 6 contains dog']

【问题讨论】:

  • 你是如何解决这个问题的?如果您发布一些代码,您将获得更快更好的答案。

标签: python list filter


【解决方案1】:

可以这么简单,使用列表推导:

>>> lst = [x for x in listB for a in listA if a in x]
>>> lst
['sentence 2 contains cat', 'sentence 6 contains dog']

编辑:这与Ollie's 的解决方案基本相同,但运行速度提高了约 8-10%。对于双向比较,只需将 if a in x 替换为 if (a in x) or (x in a)(为清楚起见添加了括号)。

【讨论】:

    【解决方案2】:

    对于一个列表中的每个项目,遍历另一个列表中的每个项目。对于每个项目,检查它是否是您想要的。

    listA = ['cat','dog','cow']
    
    listB = ['sentence 1','sentence 2 contains cat','sentence 3','sentence 4','sentence 5','sentence 6 contains dog']
    
    result = []
    
    for itemA in listA:
        for itemB in listB:
            if (itemA in itemB):
                result.append(itemB)
    

    请注意,这只适用于一种方式。如果您想包含listB 中的项目是in listA 中的项目的结果,那么您可以使用:

    listA = ['cat','dog','cow']
    
    listB = ['sentence 1','sentence 2 contains cat','sentence 3','sentence 4','sentence 5','sentence 6 contains dog']
    
    result = []
    
    for itemA in listA:
        for itemB in listB:
            if (itemA in itemB):
                result.append(itemB)
            elif (itemB in itemA):
                result.append(itemA)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 2022-09-24
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      相关资源
      最近更新 更多