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?

ilovecp3
  • 2,825
  • 5
  • 18
  • 19
  • possible duplicate of [How to find all occurrences of an element in a list?](http://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – simopopov Dec 07 '14 at 16:46

3 Answers3

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]
Korem
  • 11,383
  • 7
  • 55
  • 72
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]
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
-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
Alexandre
  • 1
  • 2