简体   繁体   中英

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

How would I 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 in Python?

For example:

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

The desired output would be: [1,2,3] as tree is found within the strings at the indices of 1, 2, 3.

I have this in the form of a function but it only returns the first instance of the sub-strings index and doesn't recognize the sub-string in a string (tree in street for example).

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

My function returns [0] but I want it to return [0,1,4]

I have tried and solved this several ways using several methods but I can't seem to return anything but [0] .

Use list comprehension with enumerate :

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

If you want to use a function:

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]

This is what you're looking for:

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

Hope this helped :) Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM