Discuss / Python / 问个问题

问个问题

Topic source

布莱嗑

#1 Created at ... [Delete] [Delete and Lock User]

想问下为什么输出的时候不是单独的1,1这类而是[1,1]呢? 我一开始觉得在triangles返回是[1]那for t in [1]为什么会输出[1]而不是1呢? 我是小白,求解答。。

#杨辉三角
def triangles():
    L=[1]
    while True:
        yield L
        L=[1]+[L[i]+L[i+1] for i in range(0,len(L)-1)]+[1]

n=0
for t in triangles():
    print(t)
    n=n+1
    if n==10:
        break

因为triangles()是一个生成器,你在for t in triangles():中是遍历的生成器中的内容,而不是在遍历list中的内容。


  • 1

Reply