首页 > 解决方案 > 如何定义一个函数包含另一个函数?

问题描述

我有一个工作功能:

def yo(a, b):
    return np.random.rand(a, b)

我想定义一个res调用yo另一个函数的新函数reshape

def res(a, b):
    maa = []
    for t in yo(a, b):
        maa.append(t[0])
        return np.reshape(maa, (a, 1))   # Calling another function

但是当我如下运行这个函数时res,我遇到了一个错误:

res(5,4)

cannot reshape array of size 1 into shape (5,1)

当我如下删除子功能时,代码运行良好。

maa = []
for t in yo(5, 4):
    maa.append(t[0])
print(np.reshape(maa,(5,1))) 

总的来说,我想了解如何在函数中定义函数。

标签: python-3.xfunctionclassnumpy

解决方案


正如 Mad Physicist 所建议的那样,您只是有一个缩进错误。return一旦 for 循环完成,就应该调用该语句:

def res(a, b):
    maa = []
    for t in yo(a, b):
        maa.append(t[0])
    return np.reshape(maa, (a, 1)) # Notice the indentation on this line

这将返回与“不使用def”时相同的结果。发生错误的原因是因为np.reshape试图仅对 . 输出的数组的单行进行操作yo


推荐阅读