Создание и возврат локальной переменной внутри функции внутри функции, которая не работает numpy - PullRequest
0 голосов
/ 21 февраля 2020

Я пытаюсь сопоставить размеры массива для произведения. Я пытаюсь создать и вернуть переменную внутри функции, но получаю следующую ошибку:

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

Кто-нибудь понимает, почему это происходит?

Ответы [ 2 ]

0 голосов
/ 21 февраля 2020

Почему вы не используете значения, возвращаемые вашей функцией?

first, second = match_lengths(a, b)

Это обычное использование функции. Если функция возвращает некоторые значения, вы присваиваете их переменным.

0 голосов
/ 21 февраля 2020

вы можете попробовать следующее, потому что return first, second пытается вернуть vriable, который не был инициализирован.

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
...