0

If I have a list

a=[1,0,0,1,0,1,1,1,0,1,0,0]

I want to find the index of 0 and 1 respectively, say in this case,

index_0 = [1,2,4,8,10,11]
index_1 = [0,3,5,6,7,9]

is there an efficient way to do this?

1

3 Answers 3

4
index_0 = [i for i, v in enumerate(a) if v == 0]
index_1 = [i for i, v in enumerate(a) if v == 1]

Or with numpy:

import numpy as np
a = np.array(a)
index_0 = np.where(a == 0)[0]
index_1 = np.where(a == 1)[0]
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect answer. I just type it the same :D
Thanks very much. One more quick question, if the length of a is large, which one is more efficient?
@user3029108 numpy will be more efficient as the array size grows.
0

using itertools.compress:

>>> a=[1,0,0,1,0,1,1,1,0,1,0,0]
>>> index_1 = [x for x in itertools.compress(range(len(a)),a)]
>>> index_1
[0, 3, 5, 6, 7, 9]
>>> index_0 = [x for x in itertools.compress(range(len(a)),map(lambda x:not x,a))]
>>> index_0
[1, 2, 4, 8, 10, 11]

you can achieve using one for loop: for better and more efficiency

>>> a=[1,0,0,1,0,1,1,1,0,1,0,0]
>>> index_0 = []
>>> index_1 = []
>>> for i,x in enumerate(a):
...     if x: index_1.append(i)
...     else: index_0.append(i)
... 
>>> index_0
[1, 2, 4, 8, 10, 11]
>>> index_1
[0, 3, 5, 6, 7, 9]

Comments

-1

Another way to do it is:

import os

a = [1,0,0,1,0,1,1,1,0,1,0,0]
index_0 = []
index_1 = []
aux = 0

for i in a:
    if i == 0:
        index_0.append(aux)
        aux += 1
    else:
        index_1.append(aux)
        aux += 1

print index_0
print index_1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.