Creating a list of functions in python (python function closure bug?)

后端 未结 3 814
陌清茗
陌清茗 2021-01-13 11:22

I understand functional programming well. I want to create a list of functions that each selects a different element of a list. I have reduced my problem to a simple example

3条回答
  •  借酒劲吻你
    2021-01-13 12:02

    How can I coerce Python to do the right thing?

    Here is one approach:

    fun_list = []
    for i in range(5):
        def fun(e, _ndx=i):
            return e[_ndx]
        fun_list.append(fun)
    
    mylist = range(10)
    print([f(mylist) for f in fun_list])
    

    This works because the default value for _ndx is evaluated and saved when the def statement for fun is executed. (In python, def statements are executed.)

提交回复
热议问题