使用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 (将#修改为@)