a-b
失败,因为自动广播发生在左侧,而不是右侧。
np.zeros((2,7,5))-np.zeros((2,7))[:,:,None]
工作
np.zeros((2,7,5))==np.zeros((2,7))[:,:,None]
和平等的测试通过元素的作品元素。
但是由于Kasra
注意到,在a==b
中,逐个元素比较将失败。显然这两个数组并不相等。返回False
与其他Python使用==
(.__eq__
方法)一致。我不知道numpy
开发者是否考虑过退回ValueError
的替代方案。
考虑一下Python中返回时比较字符串和列表:
'two'=='three'
[1,2,3]==[1]
'string'==['l','i','s','t']
我想不出哪里__eq__
返回一个错误,而不是False
的情况。但是你也许可以用这种方式编写自己的类。
为__eq__
Python文档说:
A rich comparison method may return the singleton NotImplemented if it does not implement the operation for a given pair of arguments. By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.
numpy
如下这一点 - 返回布尔数组,如果可能的话,False
否则。
bool(np.zeros((2,7,5))==np.zeros((2,7))[:,:,None])
产生错误消息:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
这是一个常见的问题SO的根。
我想,如果我想在广播不可能的时候抛出ValueError,我应该'a -b == 0' – andrew 2015-04-06 14:09:13
当测试生成整数数组的其他方法时,我会使用'=='。但如果他们是花车,allclose就更好。 '== aScalar'也是一种常见的面具。 – hpaulj 2015-04-06 17:03:37