繁体   English   中英

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

[英]how to find all the index of an element in a list Python

如果我有清单

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]

有没有一种有效的方法可以做到这一点?

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]

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

另一种方法是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM