def count():
fs = []
a=iter([i for i in range(1,4)])
for i in range(1, 4):
def pow2():
return next(a)**2
fs.append(pow2)
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
fs = []
a=iter([i for i in range(1,4)])
for i in range(1, 4):
def pow2():
return next(a)**2
fs.append(pow2)
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
2020-02-29
def count():
fs = []
for i in range(1, 4):
def f(i):
return i*i
fs.append(f(i))
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
fs = []
for i in range(1, 4):
def f(i):
return i*i
fs.append(f(i))
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
2020-02-28
已采纳回答 / 幻夜之雪
个人理解:闭包是在外层函数结束时形成的,会在此时记录闭包中的变量,参数等。f和g相当于一个闭包,所以会在return g时形成闭包保存不同的三个i值。如果没有多一层函数的话,闭包是在return fs的时候形成的,三个返回函数使用的i值都是3。
2020-02-27
def count():
return [ (lambda j: lambda: j*j)(i) for i in range(1,4) ]
f1, f2, f3 = count()
print f1(), f2(), f3()
return [ (lambda j: lambda: j*j)(i) for i in range(1,4) ]
f1, f2, f3 = count()
print f1(), f2(), f3()
2020-02-24
不是的,各位!实际上是循环时前面的函数 f 被后面的最后的函数 f 给替换了,请看以下 Python 3 代码:
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
print(f())
fs.append(f)
return fs
f1, f2, f3 = count() # 依次打印1,4,9
print(f1()) # 9
print(f2()) # 9
print(f3()) # 9
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
print(f())
fs.append(f)
return fs
f1, f2, f3 = count() # 依次打印1,4,9
print(f1()) # 9
print(f2()) # 9
print(f3()) # 9
2020-02-24
def calc_prod(lst):
return lambda : reduce(lambda x,y:x*y, lst)
f = calc_prod([1, 2, 3, 4])
print f()
return lambda : reduce(lambda x,y:x*y, lst)
f = calc_prod([1, 2, 3, 4])
print f()
2020-02-24
import time
def performance(f):
def print_time(*args):
t1=time.time()
result = f(*args)
t2=time.time()
print str(t2-t1)
return f
return print_time
@performance
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
报错
def performance(f):
def print_time(*args):
t1=time.time()
result = f(*args)
t2=time.time()
print str(t2-t1)
return f
return print_time
@performance
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
报错
2020-02-24