繁体   English   中英

在Python中查找列表中元素的索引

[英]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.

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