如何从两个数组中找到匹配元素和索引?

4
例如,
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 中是否有类似的函数?

5个回答

5

使用 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
有时候我们只是忽略了文档,而文档其实提供了我们所需要的一切 :) - Akshay Sehgal

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

从这里开始就很简单了!解压可迭代对象并检查两个元素是否相等,如果相等,则将枚举号附加到列表中!


0

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

0

使用range如下:

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

0

使用 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)]

这将导致一个元组列表,每个元组包含(索引,值)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接