lambda 函数访问外部变量 [英] lambda function accessing outside variable
问题描述
我想尝试使用匿名函数,所以我决定制作一个简单的素数查找器.这是:
I wanted to play around with anonymous functions so I decided to make a simple prime finder. Here it is:
tests = []
end = int(1e2)
i = 3
while i <= end:
a = map(lambda f:f(i),tests)
if True not in a:
tests.append(lambda x:x%i==0)
print i
print tests
print "Test: "+str(i)
print str(a)
i+=2
然而,我发现 lambda x:x%i==0
中的 i
每次都会被访问,而我希望它是一个文字数字.我怎样才能让它变成 lambda x:x%3==0
呢?
What I find however, is that the i
in the lambda x:x%i==0
is accessed each time, while i want it to be a literal number. how can I get it to become lambda x:x%3==0
instead?
推荐答案
您可以捕获"创建 lambda 时的 i
You can "capture" the i
when creating the lambda
lambda x, i=i: x%i==0
这会将 lambda 上下文中的 i
设置为等于创建它时的任何 i
.如果你愿意,你也可以说 lambda x, n=i: x%n==0
,它不是完全捕获,但它可以满足你的需要.
This will set the i
in the lambda's context equal to whatever i
was when it was created. you could also say lambda x, n=i: x%n==0
if you wanted, it's not exactly capture, but it gets you what you need.
这是一个类似于以下定义函数的查找问题:
It's an issue of lookup that's analogous to the following with defined functions:
i = "original"
def print_i1():
print(i) # prints "changed" when called below
def print_i2(s=i): # default set at function creation, not call
print(s) # prints "original" when called below
i = "changed"
print_i1()
print_i2()
这篇关于lambda 函数访问外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!