tomiris17
tomiris17

Reputation: 11

Find index of elements in array that contain a keyword

I have an array and I need to get the index of the elements which contain the word "milk".

array = ["bread ciabatta", "milk natural", "milk chocolate", "cookies chocolate", "bread banana", "bread focaccia", "milk strawberry"]

How can I accomplish this?

Upvotes: 0

Views: 658

Answers (3)

Tushar Gupta
Tushar Gupta

Reputation: 15913

One of the ways is to use enumerate inside a list-comprehension:

array = ["bread ciabatta", "milk natural", "milk chocolate", "cookies chocolate", "bread banana", "bread focaccia", "milk strawberry"]
indices = [i for i, s in enumerate(array) if 'milk' in s]
print(indices) # output [1, 2, 6]

Learn about enumerate: Docs

Upvotes: 4

nem0z
nem0z

Reputation: 1123

res = []
for i, value in enumerate(array):
    if('milk' in value):
        res.append(i)

Upvotes: 2

Salvatore Daniele Bianco
Salvatore Daniele Bianco

Reputation: 2691

import pandas as pd

array = pd.Series(["bread ciabatta", "milk natural", "milk chocolate", "cookies chocolate", "bread banana", "bread focaccia", "milk strawberry"])
array.str.match(r".*milk ")

This returns a boolean mask.

If you need indices you can do:

array.index[array.str.match(r".*milk ")]

Upvotes: 1

Related Questions