在字符串列表中查找所有子字符串,并创建新的匹配子字符串列表。用Python

在字符串列表中查找所有子字符串,并创建新的匹配子字符串列表。用Python,python,string,loops,substring,Python,String,Loops,Substring,我有一个子字符串列表和一个字符串列表。我想在字符串列表中找到所有匹配的子字符串。当在字符串中找到子字符串时,我想创建一个新的字符串列表,其中包含在每个字符串中找到的所有子字符串匹配项 例如,假设我有这些: substrings = ["word","test"] strings = ["word string one", "string two test", "word and test", "no matches in this string"] 我创建了以下内容以将子字符串与字符串匹配:

我有一个子字符串列表和一个字符串列表。我想在字符串列表中找到所有匹配的子字符串。当在字符串中找到子字符串时,我想创建一个新的字符串列表,其中包含在每个字符串中找到的所有子字符串匹配项

例如,假设我有这些:

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 


对于第一个示例,您只需在不使用换行符的情况下打印它,然后在第一个周期结束时打印换行符

如何在没有换行符的情况下打印:

您的代码没有给您想要的结果,因为您没有将多个匹配项保存在它们自己的列表中

实现所需内容的最简单方法是在循环中保留另一个列表,以包含与当前字符串匹配的子字符串

substrings = ["word","test"]

strings = ["word string one",
           "string two test",
           "word and test",
           "no matches in this string"]

result = []    

for string in strings:
    matches = []
    for substring in substrings:
        if substring in string:
            matches.append(substring)
    if matches:
        result.append(matches)
这应该给你

[['word'], ['test'], ['word', 'test']]
如果你想以你在问题中所述的格式打印这些内容,只需更改即可

result.append(matches)

这将为您提供:

word
test
word test

我想您也可以将其转换为列表comp,例如
result=[res for res in([w for w in ss if w in words]for words in string)if res]
if real want。。。
print(' '.join(matches))
word
test
word test