【发布时间】:2017-10-21 02:12:22
【问题描述】:
我有一个子字符串列表和一个字符串列表。我想在字符串列表中找到所有匹配的子字符串。当在字符串中找到子字符串时,我想创建一个新的字符串列表,其中包含在每个字符串中找到的所有子字符串匹配项。
例如,假设我有这些:
substrings = ["word","test"]
strings = ["word string one", "string two test", "word and test", "no matches in this string"]
我创建了以下内容以将子字符串与字符串匹配:
for s in strings:
for k in substrings:
if k in s:
print(k)
这给出以下输出:
word
test
word
test
我也尝试了以下方法:
matches = [x for string in strings for x in string.split() if x in substrings]
print (matches)
输出:
['word', 'test', 'word', 'test']
这些结果都不是我所追求的。由于“word”和“test”都出现在第三个字符串中,我希望得到类似于以下任一输出的内容:
word
test
word, test
或
['word', 'test', 'word test']
【问题讨论】:
标签: python string loops substring