Я пытаюсь сопоставить размеры массива для произведения. Я пытаюсь создать и вернуть переменную внутри функции, но получаю следующую ошибку:
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
Кто-нибудь понимает, почему это происходит?