python-3.x - 如何定义一个函数包含另一个函数?
问题描述
我有一个工作功能:
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)))
总的来说,我想了解如何在函数中定义函数。
解决方案
正如 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
。
推荐阅读
- javascript - 如何为引导卡创建这些动画?这对我来说非常复杂,因为我是新手
- python - 多输出 Keras 模型中的消失维度
- react-native - 使用 react-navigation 在 Drawer Navigator 中为路线设置参数
- python - Python 仅当时间是 5 时
- android - 如何检测哪个运营商(Sim1 或 Sim2)在设备中提供移动数据?
- java - Godaddy API 获取所有域自动化
- hyperledger-fabric - 未提供连接类型,未定义“x-type”属性
- javascript - Javascript数组随机选择问题
- android - 即使在打瞌睡模式下也每 15 秒获取一次位置
- angular - 错误:没有 e 的提供者!带有 prod 标志(在本地服务器上工作正常) angular4