如何解决使用Python中的循环将嵌套函数存储在字典中
我正在尝试将嵌套函数存储在字典中。为了给您一点上下文,它会发现有用的是定义一个更通用的函数,以存储的嵌套函数作为输入参数,可以使用scipy库将其最小化。
我重现了这个简单示例中未曾期望的行为:
g++ -std=c++11 -lpthread prova.cpp -o exe && ./exe
import copy
def main_func():
funcs_dict={}
nfuncs=3
for index_funcs in range(nfuncs):
#DeFinition of the nested function using lambda,and storing inside a dictionary
funcs_dict["%s"%index_funcs]=lambda x: copy.copy(index_funcs)
#display of the output of the function being stored in the dict
print("Output of the current function: %s"%funcs_dict["%s"%index_funcs](1))
#display of the output of the first function stored in the dict
print("Output of the first function: %s"%funcs_dict["0"](1))
main_func()
虽然我希望得到以下输出:
Output of the current function: 0
Output of the first function: 0
Output of the current function: 1
Output of the first function: 1
Output of the current function: 2
Output of the first function: 2
另一方面,当按以下方式手动定义字典时,不使用Output of the current function: 0
Output of the first function: 0
Output of the current function: 1
Output of the first function: 0
Output of the current function: 2
Output of the first function: 0
循环,则输出是预期的。
for
我最初是在怀疑复制/分配问题,所以我使用了def working_func():
funcs_dict={"0":lambda x:0,"1":lambda x:1,"2":lambda x:2}
for index_funcs in range(3):
print("Output of the current function: %s"%funcs_dict["%s"%index_funcs](1))
print("Output of the first function: %s"%funcs_dict["0"](1))
working_func()
方法,并且我也尝试用用copy.copy(index_funcs)
定义的函数替换lambda嵌套函数,但这无济于事。我想嵌套函数的内存分配中缺少某些东西...
提前感谢您的帮助!
马丁
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。