面试题解析

面试题

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()))
res=list(g)

# i = 0
# for i in range(8):
#	pass
# 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)))
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]

posted @ 2019-12-05 09:38  LD_Dragon_sky  阅读(86)  评论(0编辑  收藏  举报