gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:31:16 25 4
gpt4 key购买 nike

我很了解函数式编程。我想创建一个函数列表,每个函数选择列表的不同元素。我已将我的问题简化为一个简单的例子。这肯定是一个 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)

谢谢,大卫

最佳答案

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 语句被执行。)

关于python - 在 python 中创建函数列表(python 函数闭包错误?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23100401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com