本文介绍了如果测试一个数组是broadcastable到形状?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是测试一个数组是否可以被广播给定形状的最佳方式?
中的Python化的做法尝试
ING不适合我的情况下工作,因为其目的是让操作懒惰的评价。
我问如何实施 is_broadcastable
如下:
>>> X = np.ones([2,2,2])
>>> Y = np.ones([2,2])
>>> is_broadcastable(X,Y)
真正
>>> Y = np.ones([2,3])
>>> is_broadcastable(X,Y)
假
或者更好的:
>>> is_broadcastable(x.shape,y.shape)
解决方案
我真的觉得你们是在想这,为什么不保持简单?
高清is_broadcastable(SHP1,SHP2):
对于A,B拉链(SHP1 [:: - 1],SHP2 [:: - 1]):
如果一个== 1或b == 1或== A:
通过
其他:
返回False
返回True
What is the best way to test whether an array can be broadcast to a given shape?
The "pythonic" approach of try
ing doesn't work for my case, because the intent is to have lazy evaluation of the operation.
I'm asking how to implement is_broadcastable
below:
>>> x = np.ones([2,2,2])
>>> y = np.ones([2,2])
>>> is_broadcastable(x,y)
True
>>> y = np.ones([2,3])
>>> is_broadcastable(x,y)
False
or better yet:
>>> is_broadcastable(x.shape, y.shape)
解决方案
I really think you guys are over thinking this, why not just keep it simple?
def is_broadcastable(shp1, shp2):
for a, b in zip(shp1[::-1], shp2[::-1]):
if a == 1 or b == 1 or a == b:
pass
else:
return False
return True
这篇关于如果测试一个数组是broadcastable到形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!