根据文档(https://docs.scipy.org/doc/numpy/reference/ufuncs.html),如果满足下列条件之一,则可以播放两个数组:
- The arrays all have exactly the same shape.
- The arrays all have the same number of dimensions and the length of each dimensions is either a common length or 1.
- Arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy property 2.
Run Code Online (Sandbox Code Playgroud)
我试图在python中实现这一点,但在理解第二和第三条规则时遇到了麻烦.没有得到我期待的答案,但我想知道我在我的代码中犯了什么错误以及这个错误的可能解决方案.
# Broadcastable if:
# The arrays all have exactly the same shape.
if a.shape == b.shape:
result = True
# The arrays all have the same number of dimensions
elif len(a.shape) == len(b.shape):
# and the length of each dimensions is either a common length or 1.
for i in len(a.shape):
if len(a.shape[i] != 1):
result = False
else:
result = True
# Arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy property 2
elif a.shape == () or b.shape == ():
result = True
else:
result = False
return result
Run Code Online (Sandbox Code Playgroud)
这是一个简洁的表达式,用于检查两个数组是否可广播:
In [101]: import numpy as np
In [102]: a = np.zeros((3, 1, 5))
In [103]: b = np.zeros((4, 5))
In [104]: all((m == n) or (m == 1) or (n == 1) for m, n in zip(a.shape[::-1], b.shape[::-1]))
Out[104]: True
In [105]: b = np.zeros((5, 3))
In [106]: all((m == n) or (m == 1) or (n == 1) for m, n in zip(a.shape[::-1], b.shape[::-1]))
Out[106]: False
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
668 次 |
| 最近记录: |