面试题
面试题
自动发布功能测试
'''
面试题:
请写出一下代码的执行结果并解释。
'''
def multipliers():
return [lambda x, i=i: i*x for i in range(4)]
# 0, 1, 2, 3
# [func(x): return 0*x, func(x): return 1*x,
# func(x): return 2*x, func(x): return 3*x, ]
print([m(2) for m in multipliers()]) # [0, 2, 4, 6]
# [func(x): return 0*2, func(x): return 1*2,
# func(x): return 2*2, func(x): return 3*2, ]
# [0, 2, 4, 6]
# [6, 6, 6, 6]
# 闭包函数的延迟绑定
# 在内层函数执行时才会绑定变量i
def multipliers2():
list1 = []
for i in range(4):
def func(x, i=i):
return x * i
list1.append(func)
return list1
print([m(2) for m in multipliers2()]) # [0, 2, 4, 6]
# [0, 2, 4, 6]
def add(n,i):
return n+i
def test():
for i in range(4):
yield i
g=test()
for n in [1,10]:
g=(add(n,i) for i in g)
# 第一次for循环g=(add(n,i) for i in test())
# 第二次for循环g=(add(n,i) for i in (add(n,i) for i in test()))
print(n)
res=list(g)
print(res)
# i = 0
# for i in range(8):
# print(1)
#
# print(i)
g = (add(n, i) for i in g)
g = (add(n, 0), add(n, 1), add(n, 2), add(n, 3))
g = (add(n, i) for i in (add(n, 0), add(n, 1), add(n, 2), add(n, 3)))
g = (add(n,add(n,0)),add(n,add(n,1)),add(n,add(n,2)),add(n,add(n,3)))
趁自己还没死 多折腾折腾