Discuss / Python / 在generator内部通过控制n来终止循环好像不太行

### 在generator内部通过控制n来终止循环好像不太行

Topic source

#### 13个望辰

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

def triangles(max):
n=0
L=[1]
while True:
yield L
L1=L+[0]
L2=[0]+L
L=[L1[i]+L2[i] for i in range(len(L1))]
if n==max:
break
n=n+1
return


for L in triangles(10):
print(L)


#### 13个望辰

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

def triangles():
L=[1]
while True:
yield L
L1=L+[0]
L2=[0]+L
L=[L1[i]+L2[i] for i in range(len(L1))]
return


#### 用户7312310384

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

L1=L+[0]
L2=[0]+L

L1是前一行 L2是后一行的意思吗？


#### 陈卫坚-

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

1）你代码无法终止循环的原因是因为n = n +1没有放进去while 循环里面。

2）L1和L2使用[0]将两个列表错开了再相加，这个数据理解可以的。

def triangle():

L = [1]

while True:

L1 = L + [0]

L2 = [0] + L

L = [L1[i] + L2[i] for i in range(len(L1))]

yield L

if __name__ == '__main__':

for i in triangle():

print (i)

if len(i) > 10:

break

#### 翅膀的痕迹-

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

def triangles(max):

n=0

L=[1]

while True:

yield L

L1=L+[0]

L2=[0]+L

L=[L1[i]+L2[i] for i in range(len(L1))]

n=n+1

if n==max:

break

return

#### 13个望辰

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

#### _Silver1ining

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

• 1