我有一个子字符串列表和一个字符串列表。我想在字符串列表中找到所有匹配的子字符串。当在字符串中找到子字符串时,我想创建一个新的字符串列表,其中包含在每个字符串中找到的所有子字符串匹配项。
例如,假设我有这些:
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']
请您参考如下方法:
您的代码没有给您想要的结果,因为您没有将多个匹配项保存在它们自己的列表中。
实现所需内容的最简单方法是在循环中保留另一个列表以包含与当前字符串匹配的子字符串。
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)
到
print(' '.join(matches))
这会给你:
word
test
word test
