Qua*_*rgy 5 python lambda late-binding lazy-evaluation
何时进行懒惰评估?(生成器,如果是迭代器?),什么时候延迟绑定?(关闭,常规功能?)
a = [1,2,3,4]
b = [lambda y: x for x in a]
c = (lambda y: x for x in a) #lazy evaluation
d = map(lambda m: lambda y:m, a) #closure
for i in b:
print i(None)
# 4 4 4 4
for i in c:
print i(None)
# 1 2 3 4
for i in d:
print i(None)
# 1 2 3 4
Run Code Online (Sandbox Code Playgroud)
这看起来像是家庭作业,所以我不会只给你答案。您可以单步执行以下两个函数并查看值如何变化。
def make_constants_like_generator():
def make_constant(x):
def inner(y):
return x
return inner
results = []
for i in [1, 2, 3, 4]:
results.append(make_constant(i))
for f in results:
print f(None)
return results
def make_constants_like_list():
x = None
results = []
for i in [1, 2, 3, 4]:
x = i
def inner(y)
return x
results.append(inner)
for f in results:
print f(None)
return results
Run Code Online (Sandbox Code Playgroud)
延迟求值是等到最后可能的时刻才对表达式求值。相反的是热切的评价。生成器表达式是惰性的,它在迭代之前不执行任何操作。列表表达式是急切的,一旦遇到,列表就会填充值。
早期和晚期绑定与系统如何确定名称所指的内容有关。python 中的所有名称都是后期绑定的。与惰性求值相结合,这意味着名称所绑定的内容可以在使用它的表达式求值之前更改
def map(func, iter):
return (func(val) for val in iter)
Run Code Online (Sandbox Code Playgroud)