前言
生成器相比普通迭代器的实现,不会像普通迭代器生成完整集合返回,而是一边循环一边计算的机制,从而节省大量的空间。
普通迭代器
def triangles(line):
result = []
for x in range(line):
array = []
value = 1
for x1 in range(x + 1):
if x > 1 and 0 < x1 < x:
value = value + result[x - 1][x1]
array.append(value)
value = result[x - 1][x1]
else:
array.append(1)
result.append(array)
return result
生成器
def triangles(line):
last_array = None
for x in range(line):
array = []
value = 1
for x1 in range(x + 1):
if x > 1 and 0 < x1 < x:
value = value + last_array[x1]
array.append(value)
value = last_array[x1]
else:
array.append(1)
last_array = array
yield array
测试
两种实现方式,结果都是一样的
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
Process finished with exit code 0
标签:Python,生成器,value,特性,array,x1,append,result
From: https://www.cnblogs.com/grassLittle/p/17264431.html