【问题标题】:Comparing two list and returning the indices of the matched items with python比较两个列表并用python返回匹配项的索引
【发布时间】:2016-12-23 01:13:04
【问题描述】:

我有两个列表

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

问候,

【问题讨论】:

    标签: python list comparison


    【解决方案1】:

    您可以创建一个实用字典,将项目映射到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]
    

    【讨论】:

    • 它不打印任何东西,它只是运行..打印命令在哪里?或者结果保存在哪里?
    • @HamadHassan 我只是从控制台给你演示。运行脚本后,您可以通过print([index for item in b for index in d[item] if item in d]) 查看结果。
    【解决方案2】:
    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]
    

    【讨论】:

      【解决方案3】:

      其他答案的变体。我的第一个想法是将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]
      >>> 
      

      【讨论】:

        猜你喜欢
        • 2012-05-09
        • 1970-01-01
        • 2010-11-26
        • 1970-01-01
        • 1970-01-01
        • 2020-12-19
        • 2021-09-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多