在python中创建函数列表(python函数关闭错误?) [英] Creating a list of functions in python (python function closure bug?)
问题描述
我对函数式编程非常了解.我想创建一个函数列表,每个函数选择一个列表的不同元素.我已将问题简化为一个简单的例子.当然,这是一个Python错误:
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. Surely this is a Python bug:
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、4].我该如何强迫Python做正确的事? (以前没有注意到吗?还是我只是很胖?)
"Obviously" it should return [0,1,2,3,4]. It however returns [4, 4, 4, 4, 4]. How can I coerce Python to do the right thing? (Hasn't this been noticed before? Or am I just being thick?)
这是Python 3.4.0(默认值,2014年3月25日,11:07:05)
This is Python 3.4.0 (default, Mar 25 2014, 11:07:05)
谢谢, 大卫
推荐答案
我如何强迫Python做正确的事?
How can I coerce Python to do the right thing?
这是一种方法:
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])
之所以起作用,是因为在执行fun
的def
语句时会评估并保存_ndx
的默认值. (在python中,def
语句是执行的.)
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.)
这篇关于在python中创建函数列表(python函数关闭错误?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!