0

I have two lists

a = [1.1, 2.2, 5.6, 7.8,7.8, 8.6,10.2]
b = [2.2, 1.4, 1.99, 7.88, 7.8]

I want both lists to be compared and the indices of entities which delivered the same value with reference to the list a. There can be multiple hits in list a.

The results is

c= [1,3,4]  # with reference to a as 2.2 occur at location 1, 7.8 at location 3 and 4. 

I found a similar question but for case the multiple hits were not captured! and the first accepted answer does not print the indices! There is no print in the loop.

compare two lists in python and return indices of matched values

regards,

Community
  • 1
  • 1
Hamad Hassan
  • 139
  • 3
  • 13

3 Answers3

2

You can create a utility dictionary mapping the items to the list of positions in the a list:

>>> from collections import defaultdict
>>>
>>> a = [1.1, 2.2, 5.6, 7.8,7.8, 8.6,10.2]
>>> b = [2.2, 1.4, 1.99, 7.88, 7.8]
>>>
>>> d = defaultdict(list)
>>> for index, item in enumerate(a):
...     d[item].append(index)
... 
>>> [index for item in b for index in d[item] if item in d]
[1, 3, 4]
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • it does not print anything, it just run.. where is the print command? or where is the result saved? – Hamad Hassan Aug 16 '16 at 15:29
  • @HamadHassan I'm just giving you the demo from the console. You can do the `print([index for item in b for index in d[item] if item in d])` to see the results after running your script. – alecxe Aug 16 '16 at 15:31
2

A variation on the other answers. My first thought was to turn b into a set then test for membership - sets are good for membership testing.

>>> a = [1.1, 2.2, 5.6, 7.8,7.8, 8.6,10.2]
>>> b = [2.2, 1.4, 1.99, 7.88, 7.8]
>>> 
>>> b = set(b)
>>> c = [index for index, item in enumerate(a) if item in b]
>>> print(c)
[1, 3, 4]
>>> 
wwii
  • 23,232
  • 7
  • 37
  • 77
0
checker ={}
for i,item in enumerate(a):
    checker[item] = checker.get(item,[]) +[i]
reduce(lambda x,y:x+y, [checker[i] for i in b if i in checker])

[1, 3, 4]
galaxyan
  • 5,944
  • 2
  • 19
  • 43