在字符串列表中查找子字符串的所有实例和 return 找到子字符串的字符串的索引

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

如何在字符串列表中找到子字符串的所有实例以及 return 在 Python 中找到子字符串的字符串的索引?

例如:

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

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

我以函数的形式拥有它,但它只是 return 子字符串索引的第一个实例,并且无法识别字符串中的子字符串(例如 tree in street ).

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"))

我的函数 returns [0] 但我想要它 return [0,1,4]

我已经尝试并使用多种方法解决了这个问题,但我似乎无法 return 除了 [0]

使用列表理解 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]

这就是您要查找的内容:

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

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