Reputation: 3289
I have a list with elements, while some of these elements can be repeated. For example, a = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
. I want to find indices of all of these elements. Output should be like: For element 1, indices are [1, 5, 9]. For element 2, indices are [2, 6, 10] etc...
Can somebody please tell me how to do that? Note, code should be general as much as possible.
Upvotes: 1
Views: 157
Reputation:
Here is a pretty general means:
>>> 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]}
>>>
Note however that Python indexes start at 0, so the list for 1 should be [0, 4, 8]
, the list for 2 [1, 5, 9]
, etc. However, since you want the indexes to be +1, I set enumerate
to start at 1.
The above solution uses pure Python without any imports. However, if you import collections.defaultdict
, you can increase the performance:
>>> 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]}
>>>
Upvotes: 3
Reputation: 142106
As long as the item is hashable, then:
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]})
Upvotes: 2
Reputation: 2958
You can try using something like this:
def get_indexes(my_array, item):
return [i for i, e in enumerate(my_array) if e == item]
Using one of your examples:
>>> print get_indexes([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], 2)
[1, 5, 9]
Upvotes: 1
Reputation: 86128
numpy
can be useful for something like this:
>>>> 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])
Upvotes: 0
Reputation: 7931
Simple Example Using enumerate
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]
At your example you said:
For element 1, indices are [1, 5, 9]
You actually wanted index + 1! pay attention! Lists start from 0.
So to get index + 1 you can do:
myIndexes = [i+1 for i,value in enumerate(list) if value == 1]
print myIndexs
[1, 5, 9]
Upvotes: 1