python创建列表的函数,在python中创建函数列表(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])

"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?)

This is Python 3.4.0 (default, Mar 25 2014, 11:07:05)

Thanks,

David

解决方案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.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值