我是python的新手,基本上我需要过滤并获取listB中存在的listA中的所有项目。
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']
答案 0 :(得分:6)
使用列表理解可以这么简单:
>>> 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)
(为清晰起见,添加了括号)。
答案 1 :(得分: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)