简体   繁体   English

检查两个向量是否相等python

[英]check if two vectors are equal python

I have one vector called cm which does not change 我有一个名为cm的向量,它不会改变

cm = np.array([[99,99,0]])

and another vector called pt. 和另一个叫做pt的矢量。 that I want to loop through certain values. 我想循环某些值。 but when the two are equal, I want it skip over and not perform the operation. 但是当两者相等时,我希望它跳过而不执行操作。 for the sake of this post I just said to have it print out the value of pt, but I actually have a whole host of operations to run. 为了这篇文章,我只是说它打印出pt的值,但实际上我有一大堆操作要运行。 here is my code 这是我的代码

for i in range (95,103): 
    for j in range (95,103):
        pt = np.array([[i,j,0]])
        if pt == cm:
            continue
        print pt

i have tried changing the 4th line to 我已经尝试将第4行更改为

if pt.all == cm.all 

but that prints everything, including the one I want to skip and then if i turn it into 但是它会打印所有内容,包括我要跳过的内容,如果我将其转换为内容

if pt.all() == cm.all()

that also doesn't work. 这也行不通。 what is the difference between those two anyway? 这两者之间有什么区别?

does anyone know how i can fix it so that when pt = [99,99,0] it will skip the operations and go back to the beginning of the loop? 有没有人知道我怎么能修复它,所以当pt = [99,99,0]它会跳过操作并回到循环的开头? Thanks! 谢谢!

You're probably looking for (pt == cm).all() , although if floats are involved np.allclose(pt, cm) is probably a better idea in case you have numerical errors. 你可能正在寻找(pt == cm).all() ,虽然如果涉及np.allclose(pt, cm)可能是一个更好的想法,以防你有数字错误。

(1) pt.all == cm.all (1) pt.all == cm.all

This checks to see whether the two methods are equal: 这将检查两种方法是否相等:

>>> pt.all
<built-in method all of numpy.ndarray object at 0x16cbbe0>
>>> pt.all == cm.all
False

(2) pt.all() == cm.all() (2) pt.all() == cm.all()

This checks to see see whether the result of all matches in each case. 这将检查每种情况下是否all匹配的结果。 For example: 例如:

>>> pt
array([[99, 99,  0]])
>>> pt.all()
False
>>> cm = np.array([10, 10, 0])
>>> cm.all()
False
>>> pt.all() == cm.all()
True

(3) (pt == cm).all() (3) (pt == cm).all()

This creates an array testing to see whether the two are equal, and returns whether the result is all True: 这将创建一个数组测试,以查看两者是否相等,并返回结果是否全为True:

>>> pt
array([[99, 99,  0]])
>>> cm
array([[99, 99,  0]])
>>> pt == cm
array([[ True,  True,  True]], dtype=bool)
>>> (pt == cm).all()
True

One downside is that this constructs a temporary array, but often that's not an issue in practice. 一个缺点是,这构造了一个临时数组,但实际上这通常不是问题。

Aside: when you're writing nested loops with numpy arrays you've usually made a mistake somewhere. 另外:当你用numpy数组编写嵌套循环时,你通常会在某处犯错。 Python-level loops are slow, and so you lose a lot of the benefits you get from using numpy in the first place. Python级循环很慢,因此您首先使用numpy会失去许多好处。 But that's a separate issue. 但这是一个单独的问题。

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

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