Discuss / Python / 请教 append 和 insert 为何提前影响yield?

请教 append 和 insert 为何提前影响yield?

Topic source

明明每次yield a 都是在重新生成 a= [a[n]+a[n+1] for n in range(len(a)-1)]之后,为什么前面还会带上0

# -*- coding: utf-8 -*-
def triangles():
#以下填入输入框中
    a= [1]
    while 1:
        yield a
        a.insert(0,0)
        a.append(0)
        a= [a[n]+a[n+1] for n in range(len(a)-1)]
#以上填入输入框中

#运行结果
# [0, 1, 0] 
# [0, 1, 1, 0] 
# [0, 1, 2, 1, 0] 
# [0, 1, 3, 3, 1, 0] 
# [0, 1, 4, 6, 4, 1, 0] 
# [0, 1, 5, 10, 10, 5, 1, 0] 
# [0, 1, 6, 15, 20, 15, 6, 1, 0] 
# [0, 1, 7, 21, 35, 35, 21, 7, 1, 0] 
# [0, 1, 8, 28, 56, 70, 56, 28, 8, 1, 0] 
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] 
# 测试失败!     

因为如果我复制一个新的 list 然后对其进行insert 和append 操作,就不会影响结果

    t= [1]

    while 1:

        yield t

        a = t[:]

        a.insert(0,0)

        a.append(0)

        t= [a[n]+a[n+1] for n in range(len(a)-1)]

不用看了,已经终结,应该是learning.py的锅,我在Shell里面输入后是正常工作的

>>> def triangles():
    a= [1]
    while 1:
        yield a
        a.insert(0,0)
        a.append(0)
        a= [a[n]+a[n+1] for n in range(len(a)-1)]
>>> t =triangles()
>>> next(t)
[1]
>>> next(t)
[1, 1]
>>> next(t)
[1, 2, 1]
>>> next(t)
[1, 3, 3, 1]
>>> next(t)
[1, 4, 6, 4, 1]
>>> next(t)
[1, 5, 10, 10, 5, 1]
>>> next(t)
[1, 6, 15, 20, 15, 6, 1]
>>> next(t)
[1, 7, 21, 35, 35, 21, 7, 1]
>>> next(t)
[1, 8, 28, 56, 70, 56, 28, 8, 1]
>>> 

用next()调用是没问题的,但是如果print(results)就会多出来0


  • 1

Reply