在python中创建函数列表(python函数关闭错误?)


问题内容

我对函数式编程非常了解。我想创建一个函数列表,每个函数选择一个列表的不同元素。我已将问题简化为一个简单的例子。当然这是一个Python错误:

fun_list = []
for i in range(5):
    def fun(e):
        return e[i]
    fun_list.append(fun)

mylist = range(10)
print([f(mylist) for f in fun_list])

“显然”它应该返回[0,1,2,3,4]。但是,它返回[4,4,4,4,4]。如何强迫Python做正确的事?(以前没有注意到吗?还是我只是很胖?)

这是Python 3.4.0(默认值,2014年3月25日,11:07:05)

谢谢大卫


问题答案:

如何强迫Python做正确的事?

这是一种方法:

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])

之所以有效,_ndx是因为执行deffor语句时会评估并保存for的默认值fun。(在python中, 执行def语句。) __