【问题标题】:How can I find matching elements and indices from two arrays?如何从两个数组中找到匹配的元素和索引?
【发布时间】:2021-04-12 18:37:16
【问题描述】:

例如,

a = [1, 1, 2, 4, 4, 4, 5, 6, 7, 100]
b = [1, 2, 2, 2, 2, 4, 5, 7, 8, 100]

我可以使用以下方法找到匹配的元素:

np.intersect1d(a,b)

输出:

array([  1,   2,   4,   5,   7, 100])

那么,如何分别获取数组ab中匹配元素的索引呢?

IDL 中有一个函数为"match" - https://www.l3harrisgeospatial.com/docs/match.html

Python中有类似的函数吗?

【问题讨论】:

    标签: python match intersection indices idl


    【解决方案1】:

    numpy.intersect1d 中使用return_indices

    intersect, ind_a, ind_b = np.intersect1d(a,b, return_indices=True)
    

    输出:

    intersect
    # array([  1,   2,   4,   5,   7, 100])
    ind_a
    # array([0, 2, 3, 6, 8, 9], dtype=int64)
    ind_b
    # array([0, 1, 5, 6, 7, 9], dtype=int64)
    

    然后可以像这样重复使用:

    np.array(a)[ind_a]
    np.array(b)[ind_b]
    
    array([  1,   2,   4,   5,   7, 100])
    

    【讨论】:

    • 有时我们只是忽略了提供我们需要的一切的文档:)
    【解决方案2】:

    您可以使用enumerate 跟踪索引,如下所示:

    a = [1, 1, 2, 4, 4, 4, 5, 6, 7, 100]
    b = [1, 2, 2, 2, 2, 4, 5, 7, 8, 100]
    #    0  1  2  3  4  5  6  7  8   9
    
    print([i for i,x in enumerate(zip(a,b)) if x[0] == x[1]])
    
    [0, 2, 5, 6, 9]
    

    那么这里发生了什么?!

    我们正在利用惊人的enumerate 功能!此函数为可迭代对象中的每个元素生成一个元组,第一个元素是枚举(或本例中的索引),第二个元素是可迭代对象。

    zip(a,b) 的枚举如下所示

    [(0, (1, 1)), (1, (1, 2)), (2, (2, 2)), (3, (4, 2)), (4, (4, 2)), (5, (4, 4)), (6, (5, 5)), (7, (6, 7)), (8, (7, 8)), (9, (100, 100))]
    
    # lets look a little closer at one element
    (0, (1, 1))
    # ^     ^
    # index iterable
    

    从那里开始很简单!解压可迭代对象并检查两个元素是否相等,如果相等,则使用将枚举 # 添加到列表中!

    【讨论】:

      【解决方案3】:

      像这样使用range

      matching_idxs = [idx for idx in range(len(a)) if a[idx] == b[idx]] 
      print(matching_idxs)
      # [0, 2, 5, 6, 9]
      

      【讨论】:

        【解决方案4】:

        使用enumeratezip

        a = [1, 1, 2, 4, 4, 4, 5, 6, 7, 100]
        b = [1, 2, 2, 2, 2, 4, 5, 7, 8, 100]
        
        output = [(i, x) for i, (x, y) in enumerate(zip(a, b)) if x == y]
        
        print(output)
        

        [(0, 1), (2, 2), (5, 4), (6, 5), (9, 100)]
        

        这导致元组列表为(index, value)

        【讨论】:

          【解决方案5】:

          zip 函数的帮助下并行循环两个列表非常简单:

          >>> count = 0
          >>> indices = []
          >>> for x, y in zip(a, b):
              if x == y:
                  indices.append(count)
              count += 1
          
              
          >>> indices
          [0, 2, 5, 6, 9]
          

          【讨论】:

            猜你喜欢
            • 2020-06-01
            • 2018-08-21
            • 2017-03-06
            • 1970-01-01
            • 2021-05-19
            • 1970-01-01
            • 2018-12-29
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多