繁体   English   中英

在Python中比较两个2D元组和numpy

[英]Comparing Two 2-D tuples with numpy in Python

我有两个嵌套的元组,分别名为coordcoord2我想看看第一个元组中的一组坐标是否与另一个元组中的一组坐标相匹配,而不管索引如何。

例如,

coord[0][1] = 127,
coord[0][2] = 128,
coord[0] = 127,128,129....
coord[1][0] = 302,
coord[1] = 302,303,304 ....

现在,我可以看到每个索引是否与另一个元组的索引完全匹配,但是看不到另一个中是否存在一个集合。 这是我的代码:

for i in range(60):
if (coord[0][i]) == (coord2[0][i]) and (coord[1][i]) == (coord2[1][i]):
    print(coord[0][i])
    print(coord[1][i])
    count += 1
    total += 1
else:
    total += 1

我应该怎么做呢? 我在python中使用numpy数组很新

我已经写了一些新代码,

for i in range(60):
    if coord2[0][i] and coord2[1][i] in coord:
        count += 1
        total += 1
    else:
        total += 1

在我看来,这应该告诉我第二个元组中是否有任何一组坐标。 但是我遇到一个错误,说ValueError:具有多个元素的数组的真值不明确。 使用a.any()或a.all()

其实想通了。

for i in range(200):
    if (coord2[0][i]) in coord[0] and coord2[1][i] in coord[1]:
        count += 1
        total += 1
    else:
        total += 1

如果您只是想知道一个矩阵中的任何坐标是否存在于另一个矩阵中,则这是一种实现方法。

import itertools
import numpy

首先让我们获取矩阵的所有可能的索引组合

idx = tuple(e for e in itertools.product(range(len(coord)), repeat=2))

((0, 0),
 (0, 1),
 (0, 2),
 (0, 3),
 (1, 0),
 (1, 1),
 (1, 2),
 (1, 3),
 (2, 0),
 (2, 1),
 (2, 2),
 (2, 3),
 (3, 0),
 (3, 1),
 (3, 2),
 (3, 3))

然后让我们比较两个索引矩阵,看看是否有其他点存在

coord = np.arange(16).reshape(4,4)

coord1 = np.random.randint(1, size=(4,4))

np.equal([coord[_idx] for _idx in idx],[coord1[_idx] for _idx in idx])

array([ True, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False], dtype=bool)

编辑:如果您只是想要出现的次数,那么它将变为

np.sum(np.equal([coord[_idx] for _idx in idx],[coord1[_idx] for _idx in idx]))

>>1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM