3 回答
TA贡献1826条经验 获得超6个赞
Python 的闭包是后期绑定的。这意味着在调用函数时会查找闭包中使用的变量的值。
为了避免后期绑定效果,您可以使用带有默认参数的 lambda:
index = 1
test = lambda t, index=index: t[index]+1 # binds index at definition time
index = 0
print(test([5, 0])) # 1
TA贡献2021条经验 获得超8个赞
index既不是参数也不是局部变量,test()因此它确实被解析为非局部变量(+> 它在封闭范围内查找)。
简单的解决方案是使用默认值创建index一个参数,test捕获index定义时的值:
index = 1
test = lambda t, _index=index: t[_index]+1
index = 0
print(test([5, 0]))
TA贡献1854条经验 获得超8个赞
您可以使用operator.itemgetter创建一个可调用对象,该对象从列表中提取第n个项目:
from operator import itemgetter
index = 1
get_val = itemgetter(index)
test = lambda t: get_val(t) +1
index = 0
print(test([5, 0])) # 1
但是这里没有理由lambda声明,你可以显式定义一个函数:
def test(t):
return get_val(t) + 1
添加回答
举报
