# 生成器
g = (i * i for i in range(10) if i % 2 == 0)
for i in g:
print(i)
# 用生成器实现斐波拉契数列
def fib(num):
n, a, b = 0, 0, 1
while n < num:
yield b
a, b = b, b + a
n += 1
for i in fib(10):
print(i)
# 用生成器实现杨辉三角
def pascal_triangle():
L = [1]
while 1:
yield L
L.append(0) # 卧槽,这点完全想不到!
L = [L[i - 1] + L[i] for i in range(len(L))]
n = 0
for i in pascal_triangle():
print(i)
n+=1
if n == 10:
break
网友评论