如何用lambda 优化下面代码



 def count():
    fs = []
    def f(n):
        def j():
            return n * n
        return j
    for i in range(1, 4):
        fs.append(f(i))
    return fs

f1, f2, f3 = count()

python3.x python

PPPoE 9 years, 3 months ago

 def count():
    fs = []
    def f(n):
        return lambda : n * n
    for i in range(1, 4):
        fs.append(f(i))
    return fs

f1, f2, f3 = count()

你如果要保持闭包,且调用f1(),f2()...时不用传参数,就这样了。但是我不明白你这样闭包有什么意义。


 def count():
    for i in range(1, 4):
        yield i*i

直接返回值不好吗?

嘟嘟哒哒零 answered 9 years, 3 months ago

Your Answer