【发布时间】:2020-06-05 10:31:45
【问题描述】:
我正在尝试为一件作品匹配数组尺寸。我正在尝试在函数内创建并返回一个变量,但收到以下错误:
UnboundLocalError: local variable 'first' referenced before assignment
我不明白这一点,因为第一次遇到这个词实际上是我在定义它是什么。
我不能使用global,因为它是函数中的函数。我的代码如下,应该是可重现的。
a= np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9), (10,11,12)])
b = np.array([(10, 20, 30), (40, 50, 60)])
def broadcast(a, b):
def match_lengths(a_ar, b_ar):
a_shape = list(np.shape(a_ar))
b_shape = list(np.shape(b_ar))
if len(a_shape) == len(b_shape):
print('Already same dimensions')
pass
else:
if len(a_shape) > len(b_shape):
extra_dims = len(a_shape) - len(b_shape)
smaller_arr = b_shape
else:
extra_dims = len(b_shape) - len(a_shape)
smaller_arr = a_shape
dim = (1,)
add_dims = dim * extra_dims
shapes = add_dims + tuple(smaller_arr)
if smaller_arr == a_shape:
first = np.reshape(a_ar, shapes)
else:
second = np.reshape(b_ar, shapes)
return first, second
match_lengths(a, b)
a_shape = list(np.shape(first))
b_shape = list(np.shape(second))
return a_shape, b_shape
有人知道为什么会这样吗?
【问题讨论】:
标签: python function numpy broadcast