如何在列表中找到与另一个列表中的字符串或子字符串匹配的字符串

时间:2016-07-19 15:19:00

标签: python

如何在List1中找到一个字符串,它是List2中任何字符串的子字符串?两个列表可以有不同的长度。

说我有:

List1=['hello', 'hi', 'ok', 'apple']

List2=['okay', 'never', 'goodbye']

我需要它返回' ok',因为它是list1中唯一与list2匹配的字符串。

3 个答案:

答案 0 :(得分:8)

您可以将列表理解用作:

[x for x in List1 for y in List2 if x in y]

答案 1 :(得分:1)

如果你想知道list1中的字符串是否在list2中,你可以

for s in List1:
    if s in List2:
        print("found s in List2")

答案 2 :(得分:0)

我写了这段代码来实现

List1=['hello', 'hi', 'ok', 'apple']
List2=['ok', 'never', 'goodbye']
i=[]
for j in List1:
    for k in List2:
        if j==k:
            i.append(j)

print i
相关问题