有两个包含以下内容的列表:
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']
答案 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']