如何在列表Python中查找元素的所有索引

时间:2014-12-07 16:42:01

标签: python list

如果我有一个清单

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

我想分别找到0和1的索引,比如在这种情况下,

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

有一种有效的方法吗?

3 个答案:

答案 0 :(得分: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]

或者是numpy:

import numpy as np
a = np.array(a)
index_0 = np.where(a == 0)[0]
index_1 = np.where(a == 1)[0]

答案 1 :(得分:0)

使用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]

你可以使用一个for循环:更好,更高效

>>> 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]

答案 2 :(得分:-1)

另一种方法是:

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