简体   繁体   English

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

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

I have two nested tuples named coord and coord2 and I want to see if one set of coordinates in the first tuple match another in the other tuple regardless of the index. 我有两个嵌套的元组,分别名为coordcoord2我想看看第一个元组中的一组坐标是否与另一个元组中的一组坐标相匹配,而不管索引如何。

For example, 例如,

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

Right now I can see if each index matches the other tuple's index exactly, but not whether one set exists in the other. 现在,我可以看到每个索引是否与另一个元组的索引完全匹配,但是看不到另一个中是否存在一个集合。 Here is my code: 这是我的代码:

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

How should I go about doing this? 我应该怎么做呢? I am pretty new to using numpy arrays in python 我在python中使用numpy数组很新

I have written some new code like so, 我已经写了一些新代码,

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

In my mind this should tell me if any set of coordinates in the second tuple is in the first one. 在我看来,这应该告诉我第二个元组中是否有任何一组坐标。 But I am running into an error saying, ValueError: The truth value of an array with more than one element is ambiguous. 但是我遇到一个错误,说ValueError:具有多个元素的数组的真值不明确。 Use a.any() or a.all() 使用a.any()或a.all()

Actually figured it out. 其实想通了。

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

If you simply want to know if any of the coordinates of one matrix exist in another then this is one way of doing it. 如果您只是想知道一个矩阵中的任何坐标是否存在于另一个矩阵中,则这是一种实现方法。

import itertools
import numpy

First let's get all possible index combinations for the matrices 首先让我们获取矩阵的所有可能的索引组合

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

Then let's compare the two indexed matrices and see if any of the points exist in the other 然后让我们比较两个索引矩阵,看看是否有其他点存在

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)

Edit: If you simply want the number of occurrences then it becomes this 编辑:如果您只是想要出现的次数,那么它将变为

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