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

后端 未结 3 812
陌清茗
陌清茗 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:03

    Surely this is a Python bug...

    This is a misunderstanding of scopes. Since all five instances of fun() are defined in the same scope, they will all have the same value of all names in that scope, including i. In order to fix this you need to separate the value used from the scope containing the loop itself. This can be done by defining the function within a completely different scope.

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

提交回复
热议问题