在numpy不工作的函数中创建并返回函数内部的局部变量



我正在尝试为一件作品匹配数组维度。我试图在函数中创建并返回一个变量,但我收到了以下错误:

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

有人明白为什么会发生这种事吗?

您可以尝试以下操作吗?因为return first, second正试图返回一个未初始化的vrable。

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(fun, a, b):
def match_lengths(a_ar, b_ar):
first, second = np.array([]), np.array([])
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
first, second = match_lengths(a, b)
a_shape = list(np.shape(first))
b_shape = list(np.shape(second)) 
return a_shape, b_shape

为什么不使用函数返回的值?

first, second = match_lengths(a, b)

这是正常的函数用法。如果函数返回一些值,则将它们分配给变量。

最新更新