[英]How to make an index static for a python lambda expression
Say I have these lines of code 说我有这些代码行
index = 1
test = lambda t : t[index]+1
index = 0
print(test([5, 0]))
The result is 6, I would expect the result to be 1. How can I make the index inside the lambda expression static without writing t[1]+1
, ie using a variable? 结果是6,我希望结果是1。如何在不编写
t[1]+1
(即使用变量)的情况下使lambda表达式内的索引静态化?
Python's closures are late binding . Python的闭包是后期绑定 。 This means that the values of variables used in closures are looked up at the time the function is called.
这意味着在调用函数时会查询闭包中使用的变量的值。
To avoid the late binding effect you can use a lambda with a default arg: 为了避免后期绑定效果,您可以使用带有默认arg的lambda:
index = 1
test = lambda t, index=index: t[index]+1 # binds index at definition time
index = 0
print(test([5, 0])) # 1
index
is neither an argument nor a local variable in test()
so it is indeed resolved as aa nonlocal (+> it's looked up in the enclosing scopes). index
在test()
既不是参数也不是局部变量,因此它确实被解析为非局部变量(+>在封闭范围内查找)。
The simple solution is to make index
an argument of test
with a default value capturing the value of index
at definition time: 一种简单的解决方案是使
index
成为test
参数,并使用默认值捕获定义时index
的值:
index = 1
test = lambda t, _index=index: t[_index]+1
index = 0
print(test([5, 0]))
You can use a lambda
to return a lambda
: 您可以使用
lambda
返回lambda
:
test = (lambda index: lambda t: t[index] + 1)(index)
This way the index
variable is local to the returned lambda function. 这样,
index
变量对于返回的lambda函数而言是本地的。
You can use operator.itemgetter
to create a callable object which extracts the n th item from a list: 您可以使用
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
But there's no reason here for a lambda
statement, you can define a function explicitly: 但是这里没有理由使用
lambda
语句,您可以显式定义一个函数:
def test(t):
return get_val(t) + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.