Discuss / Python / 有个疑惑想请教下大佬,这里用next,为什么不行,然后加上print就可以了,但是不论多少个print都是一样的[1],再接上下面给的又能得到正确答案,我是不是哪里搞混了

有个疑惑想请教下大佬,这里用next,为什么不行,然后加上print就可以了,但是不论多少个print都是一样的[1],再接上下面给的又能得到正确答案,我是不是哪里搞混了

Topic source

def triangles():

    L =[1]

    while True:

        yield L[:]

        L.append(0)

        L=[L[i]+L[i-1] for i in range(len(L))]

next(triangles())

print(next(triangles()))

print(next(triangles()))

这个按我理解,是每次调用 triangles(),定义的都是新的迭代器。

print(next(triangles()), next(triangles()), next(triangles()))
g = triangles()
print(next(g),next(g),next(g))

输出结果是

[1] [1] [1]

[1] [1, 1] [1, 2, 1]

同理,对正文所定义的 fib(max) 函数,用以下方式调用

print(type(fib(3)), next(fib(3)), *fib(3))

输出结果就是

<class 'generator'> 1 1 1 2


  • 1

Reply