我有一个子字符串列表和一个字符串列表。我想在字符串列表中找到所有匹配的子字符串。当在字符串中找到子字符串时,我想创建一个新的字符串列表,其中包含每个字符串中找到的所有子字符串匹配项。
例如,假设我有这些:
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
关于python - 查找字符串列表中的所有子字符串并创建一个新的匹配子字符串列表。在Python中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44095595/