[英]Find indices of elements in a list in Python
我有一個包含元素的列表,而其中一些元素可以重復。 例如, a = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
。 我想找到所有這些元素的索引。 輸出應類似於: For element 1, indices are [1, 5, 9]. For element 2, indices are [2, 6, 10] etc...
For element 1, indices are [1, 5, 9]. For element 2, indices are [2, 6, 10] etc...
有人可以告訴我該怎么做嗎? 注意,代碼應盡可能通用。
這是一個非常通用的方法:
>>> lst = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
>>> dct = {x:[] for x in lst}
>>> for x,y in enumerate(lst, 1):
... dct[y].append(x)
...
>>> dct
{1: [1, 5, 9], 2: [2, 6, 10], 3: [3, 7, 11], 4: [4, 8, 12]}
>>>
但是請注意,Python索引從0開始,因此1的列表應為[0, 4, 8]
,2的列表應為[1, 5, 9]
等。但是,由於您希望索引為+1,我將enumerate
設置為從1開始。
上面的解決方案使用沒有任何導入的純Python。 但是,如果導入collections.defaultdict
,則可以提高性能:
>>> from collections import defaultdict
>>> dct = defaultdict(list)
>>> for x,y in enumerate(lst, 1):
... dct[y].append(x)
...
>>> dct
{1: [1, 5, 9], 2: [2, 6, 10], 3: [3, 7, 11], 4: [4, 8, 12]}
>>>
只要該項是可哈希的,則:
from collections import defaultdict
data = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
dd = defaultdict(list)
for idx, item in enumerate(data):
dd[item].append(idx)
# defaultdict(<type 'list'>, {1: [0, 4, 8], 2: [1, 5, 9], 3: [2, 6, 10], 4: [3, 7, 11]})
您可以嘗試使用以下方法:
def get_indexes(my_array, item):
return [i for i, e in enumerate(my_array) if e == item]
使用您的示例之一:
>>> print get_indexes([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], 2)
[1, 5, 9]
使用枚舉的簡單示例
list = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
myIndexes = [i for i,value in enumerate(list) if value == 1]
print myIndexs
[0,4,8]
在您的示例中,您說:
對於元素1,索引為[1、5、9]
您實際上想要索引+ 1! 請注意! 列表從0開始。
因此,要獲取索引+1,您可以執行以下操作:
myIndexes = [i+1 for i,value in enumerate(list) if value == 1]
print myIndexs
[1、5、9]
numpy
對於如下所示可能很有用:
>>>> import numpy as np
>>> a
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
>>> np.where(np.array(a) == 1)[0]
array([0, 4, 8])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.