在列表中查找字符串的列表理解?

时间:2019-05-20 12:14:54

标签: python list-comprehension

我想通过列表理解力来应对一个小挑战。

示例:

all_words = ["dongtestdong", "hello", "i", "am", "dongtest2dong", "like", "to", 
             "make", "dongtest3dong", "dance", "tonight" "do"]
split_list = ["test", "test2", "test3"]

现在我要做的是-每当我在all_words中找到一个字符串,该字符串与split_list中的任何字符串都匹配时,我想获取“ test”字符串以及all_words字符串中的下两个字符串。

因此在上面的示例中,新字符串为:

new_string = ["dongtestdong", "hello", "i", "dongtest2dong", "like", "to", 
              "dongtest3dong", "dance", "tonight"]

2 个答案:

答案 0 :(得分:2)

这是一种未优化的列表理解:

new_list = [item for sublist in set([tuple(all_words[i:i+3]) for i,j in enumerate(all_words) for k in split_list if k in j]) for item in sublist]

输出

["dongtestdong", "hello", "i", "dongtest2dong", "like", "to", "dongtest3dong", "dance", "tonight"]

答案 1 :(得分:0)

from functools import reduce

result = [all_words[ind:ind+3] for ind, x in enumerate(all_words) if any(y in x for y in split_list)]

#flatten your list if wanted
result = list(reduce(lambda x, y: x+y, result))