【问题标题】:Find all instances of a sub-string in a list of strings and return the index of the string where the sub-string is found在字符串列表中查找子字符串的所有实例,并返回找到子字符串的字符串的索引
【发布时间】:2021-12-18 23:44:27
【问题描述】:

如何在字符串列表中找到子字符串的所有实例并返回在 Python 中找到子字符串的字符串的索引?

例如:

sub_string = "tree"
my_list = ["banana", "tree", "trees", "street"]

所需的输出将是:[1,2,3],因为在字符串中的索引 1、2、3 处找到树。

我有这个函数的形式,但它只返回子字符串索引的第一个实例,并且不识别字符串中的子字符串(例如街道上的树)。

def inside_search(a_list, search_term):
    if search_term in a_list:
        index = a_list.index(search_term, 0, -1)
        return [index]
    else:
        return []

cats_and_dogs_list = ["cat", "cats", "dog", "dogs", "catsup"]
print(inside_search(cats_and_dogs_list, "cat"))

我的函数返回[0],但我希望它返回[0,1,4]

我已经尝试并使用多种方法解决了这个问题,但除了[0],我似乎无法返回任何内容。

【问题讨论】:

    标签: python list indexing


    【解决方案1】:

    enumerate使用列表推导:

    >>> [i for i, w in enumerate(my_list) if sub_string in w]
    [1, 2, 3]
    

    如果要使用函数:

    def inside_search(a_list, search_term):
        result = list()
        for i, word in enumerate(a_list):
            if search_term in word:
                result.append(i)
        return result
    
    >>> inside_search(cats_and_dogs_list, "cat")
    [0, 1, 4]
    

    【讨论】:

      【解决方案2】:

      这就是你要找的东西:

      print([my_list.index(item) for item in my_list if sub_string in item])
      

      希望这会有所帮助 :) 干杯!

      【讨论】:

        猜你喜欢
        • 2014-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 2013-07-01
        • 1970-01-01
        • 2012-05-16
        相关资源
        最近更新 更多