【发布时间】:2018-09-17 02:05:37
【问题描述】:
我有两个列表,如下所示。我想查找第一个列表中的字符串是否在第二个列表中的任何字符串中。出于某种原因,当我尝试运行它时,我得到了一个空列表。
例如:在list5中,字符串'apple'在list6的'I ate an apple'中。
list5 = ['apple', 'mango', 'sherbet']
list6 = ['I ate an apple', 'I ate two apples', 'I love mango']
print ([x for i,x in enumerate(list5) if x in list6])
对于整数列表,完全相同的事情运行顺利。是否有不同的方式来处理字符串?
list7 = [1, 2, 3, 4, 5]
list8 = [1, 2]
print ([x for i,x in enumerate(list7) if x in list8])
【问题讨论】:
-
你正在检查'apple'本身是否是list6的成员,你想检查'apple'是否是list6中任何字符串的子字符串
-
你会一直处理第一个字符串列表中的单个单词吗?例如,您能否在第一个列表中包含
['an apple', 'mango', 'sherbert']并期望在第二个列表中的任何字符串中匹配'an apple'?
标签: python string python-3.x list list-comprehension