【问题标题】:Find all substrings in list of strings and create a new list of matching substrings. in Python在字符串列表中查找所有子字符串并创建一个新的匹配子字符串列表。在 Python 中
【发布时间】: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


    【解决方案1】:

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

    实现您正在寻找的最简单的方法是在循环中保留另一个列表以包含与当前字符串匹配的子字符串。

    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
    

    【讨论】:

    • 如果你真的想要的话,我想你也可以把它转换成一个列表组合,比如result = [res for res in ([w for w in ss if w in words] for words in strings) if res]...
    【解决方案2】:

    对于第一个示例,您只需在没有换行符的情况下打印它,然后在第一个循环结束时打印换行符。

    如何在没有换行符的情况下打印: How to print without newline or space?

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 2023-04-03
      • 2012-05-16
      • 2013-06-18
      • 1970-01-01
      • 2018-09-27
      • 2021-12-18
      • 2013-05-27
      相关资源
      最近更新 更多