0

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?

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.