如果存在第二个列表中的元素,如何遍历两个列表并从第一个列表中提取元素?

时间:2018-07-29 09:33:41

标签: python list

有两个包含以下内容的列表:

list1 = ['This egg is delicious', 'I love blueberry waffles', 'Eating blueberry waffles has always been my favorite', 'I recommend the pork belly', 'Chocolate Sundae hits the spot'] 

list2 = ['egg','Chocolate Sundae']

我希望结果是这样的。如您所见,list2包含单词,我希望它循环遍历并从list1提取元素,因为它具有list2单词。我该如何实现这一目标?

['This egg is delicious','Chocolate Sundae hits the spot'] 

2 个答案:

答案 0 :(得分:1)

list3 =[]

for i in list1:
  for k in list2:
    if k in i:
      list3.append(i)

print(list3)

答案 1 :(得分:0)

使用正则表达式。 re.search

例如:

import re
list1 = ['This egg is delicious', 'I love blueberry waffles', 'Eating blueberry waffles has always been my favorite', 'I recommend the pork belly', 'Chocolate Sundae hits the spot']
list2 = ['egg','Chocolate Sundae']

checkVal = "|".join(list2)
print([i for i in list1 if re.search(checkVal, i)])

输出:

['This egg is delicious', 'Chocolate Sundae hits the spot']