簡體   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