pynovice
pynovice

Reputation: 7752

Get the index of a list from another list in python

I have two list like this:

>>> a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']
>>> b = ['a', 'b', 'c', 'd']

By using b I want to get the result like this:

a -> 0, 2, 5
b -> 1, 4
c -> 3
d -> 6

Tried using enumerate()

>>> for i, j in enumerate(b):
...     a[i]
... 
'a'
'b'
'a'
'c'

Didn't work.

Upvotes: 0

Views: 106

Answers (8)

ovgolovin
ovgolovin

Reputation: 13410

O(n+m) algorithm (many other answers seem to have O(n*m) complexity):

>>> from collections import defaultdict
>>> D = defaultdict(list)
>>> for i,item in enumerate(a): D[item].append(i)  
>>> for item in b:
    print('{} -> {}'.format(item, D[item]))   

a -> [0, 2, 5]
b -> [1, 4]
c -> [3]
d -> [6]

Upvotes: 0

ndpu
ndpu

Reputation: 22561

>>> [(char, [i for i,c in enumerate(a) if c==char]) for char in b]
[('a', [0, 2, 5]), ('b', [1, 4]), ('c', [3]), ('d', [6])]

or

>>> dict((char, [i for i,c in enumerate(a) if c==char]) for char in b)
{'a': [0, 2, 5], 'c': [3], 'b': [1, 4], 'd': [6]}

Upvotes: 0

fyr91
fyr91

Reputation: 1293

Thanks for all the enumerate :), here is something pretty interesting I found last time trying to answer something quite the same, that is to use index() function to return multiple positions.

a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']
b = ['a', 'b', 'c', 'd']
for item in b:
    index = []
    start = -1
    while True:
        #also take care of the case where item in b is not in a
        try:
            start = a.index(item, start+1)
            index.append(start)
        except ValueError:
            break;
        print item, index

Result

a [0, 2, 5]
b [1, 4]
c [3]
d [6]

a.index(b, position) defines the starting point of indexing.

Upvotes: 0

BlackMamba
BlackMamba

Reputation: 10254

import collections
def getIndex(ListA, ListB):
    res = collections.defaultdict(list)
    for element in ListB:
        for (i, v) in enumerate(ListA):
            if element == v:
                res[v].append(i)

    for key, value in sorted(res.items(), key = lambda d : d[0]):
        print(key, " -> ", ",".join([str(i) for i in value]))

a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']
b = ['a', 'b', 'c', 'd']
getIndex(a, b)

The output is:

a  ->  0,2,5
b  ->  1,4
c  ->  3
d  ->  6

Upvotes: 0

slider
slider

Reputation: 12990

Try

>>> a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']
>>> b = ['a', 'b', 'c', 'd']
>>> indices = [ i for i, x in enumerate(a) if x == b[0] ]
>>> indices
[0, 2, 5]

You can change b[0] to whatever letter you want the indices for.

Explanation:

Let each element of enumerate(a) be of the form (i,x). So, indices is an array of all i in enumerate(a) such that x equals b[0] (or whatever other letter you want it to be).

Upvotes: 0

Sravan K Ghantasala
Sravan K Ghantasala

Reputation: 1318

I ll do it like...

Code:

a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']
b = ['a', 'b', 'c', 'd']

for item in b:
    print item + ':' + ','.join([str(i) for i,val in enumerate(a) if item==val])   

Output:

a:0,2,5
b:1,4
c:3
d:6  

Hope this helps :)

Upvotes: 0

Inbar Rose
Inbar Rose

Reputation: 43437

def get_all_indexes(lst, item):
    return [i for i, x in enumerate(lst) if x == item]

a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']
b = ['a', 'b', 'c', 'd']

for item in b:
    print item, get_all_indexes(a, item)

Result:

>>> 
a [0, 2, 5]
b [1, 4]
c [3]
d [6]

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113905

You were right to use enumerate, though you didn't quite use it exactly right

In [5]: a = ['a', 'b', 'a', 'c', 'b', 'a', 'd']

In [6]: b = ['a', 'b', 'c', 'd']

In [7]: for char in b: print char, [i for i,c in enumerate(a) if c==char]
a [0, 2, 5]
b [1, 4]
c [3]
d [6]

Upvotes: 5

Related Questions