比较两个列表并返回 python 匹配项的索引

Comparing two list and returning the indices of the matched items with python

我有两个列表

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]

我希望比较两个列表以及参考列表 a 传递相同值的实体的索引。列表 a 中可以有多个命中。

结果是

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

我发现了一个类似的问题,但是为了防止多次点击没有被捕获!并且第一个接受的答案不打印索引!循环中没有打印。

compare two lists in python and return indices of matched values

问候,

您可以创建一个实用字典,将项目映射到 a 列表中的位置列表:

>>> 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]
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]

其他答案的变体。我的第一个想法是将 b 变成一个集合,然后测试成员资格 - 集合有利于成员资格测试。

>>> 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]
>>>