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

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

    You can do this using the itemgetter:

    from operator import itemgetter
    fun_list = []
    for i in range(5):
        fun_list.append(itemgetter(i))
    
    mylist = range(10)
    print([f(mylist) for f in fun_list])
    

    In your case, you are assigning a function to all elements referencing a global i with the value of i at the time of the call, which is 4 for all calls. You need some sort of currying.

    Same without the itemgetter:

    def indexer(i): return lambda y: y[i]
    
    fun_list = []
    for i in range(5):
        fun_list.append(indexer(i))
    
    mylist = range(10)
    print([f(mylist) for f in fun_list])
    

提交回复
热议问题