Efficient approach of getting the list index if certain element exist in the list of strings with Python

Viewed 19

Given a list of strings, the objective is to get the index for occurrence of 0.

To achieve this objective, the following code is propose

txt=['-100:200','-15:0','0:15','30:45']

all_t=[[int(idx) for idx in t.split(":")] for t in txt]
s_val=[]
for idx,mm in enumerate(all_t):
    if 0 in mm:
        s_val.append(idx)

Expected output

s_val=[1, 2]

However, I wonder the is build-in or more compact/efficient approach to achieve the above objective?

1 Answers
txt=['-100:200','-15:0','0:15','30:45']

print ([i for i in range(len(txt)) if '0' in txt[i].split(":")])

Output:

[1,2]

You use list comprehension to iterate through each element in txt by index i.

Then you just check the condition: is '0' in the list from the .split(":") of this single element at the given index.

Related