在python中创建函数列表(python函数关闭错误?) [英] Creating a list of functions in python (python function closure bug?)

查看:116
本文介绍了在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])

显然",它应该返回[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])

之所以起作用,是因为在执行fundef语句时会评估并保存_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆