I have a list that is basicaly zeroes and ones, I want to grab all the indices of the ones from that list. How do I do it, plz. If possible, w/o loops.
list_example = [1,0,0,1,0,0,0,1,1,0]
I have a list that is basicaly zeroes and ones, I want to grab all the indices of the ones from that list. How do I do it, plz. If possible, w/o loops.
list_example = [1,0,0,1,0,0,0,1,1,0]
You could use np.argwhere()
to obtain incides in a list whose elements satisfy a certain condition.
Below's the code:
import numpy as np
np.argwhere(np.array(list_example))[0]
Output:
[0, 3, 7, 8]
where we obtain indices of all non-zero elements in list_example
. For more specific condition checking, you could use,
np.argwhere(np.array(list_example==1))
you can use list comprehension:
ones_indices = [i for i, e in enumerate(list_example) if e == 1]
Without loops or imports you can do it this way:
list(zip(*list(filter(lambda x: x[1] == 1, enumerate(list_example)))))[0]
# (0, 3, 7, 8)
or if you want lists:
list(map(list, zip(*list(filter(lambda x: x[1] == 1, enumerate(list_example))))))[0]
# [0, 3, 7, 8]
my attempt so far:
g = [0,0,1,0,1,0,0,1,1,0,0,0,1,0]
u = []
for i in g:
if i == 1:
u.append(g.index (i))
print (u)
input ('continue')