生成器: 生成器是一个可迭代对象。 生成器本质上就是一个函数,它记住了上一次返回时在函数体中的位置。 对生成器函数的第二次(或第n次)调用,跳转到函数上一次挂起的位置。 而且记录了程序执行的上下文。 生成器不仅“记住”了它的数据状态,生成还记住了程序执行的位置。
以下是生成器的一些用法笔记:
L = [x * x for x in range(10)]
print(L)
g = (x * x for x in range(10))
print(g)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
for n in g:
print(n)
print("*****************************************************")
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'
"""
a, b = b, a + b 相当于
t = (b, a + b) # t是一个tuple
a = t[0]
b = t[1]
"""
print(fib(5))
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
print("****************************************************")
def odd():
print('step 1')
yield 1
print('step 2')
yield 3
print('step 3')
yield 5
o = odd()
print(next(o))
print(next(o))
print(next(o))
g = fib(6)
while True:
try:
x = next(g)
print('g:', x)
except StopIteration as e:
print('Generator return value:', e.value)
break
"""
杨辉三角定义如下:
1
/ \
1 1
/ \ / \
1 2 1
/ \ / \ / \
1 3 3 1
/ \ / \ / \ / \
1 4 6 4 1
/ \ / \ / \ / \ / \
1 5 10 10 5 1
把每一行看做一个list,试写一个generator,不断输出下一行的list:
"""
def triangles():
arr = [1]
while True:
yield arr
arr = [1] + [arr[i] + arr[i + 1] for i in range(len(arr) - 1)] + [
1]
n = 0
results = []
for t in triangles():
results.append(t)
n = n + 1
if n == 10:
break
for t in results:
print(t)
if results == [
[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]
]:
print('测试通过!')
else:
print('测试失败!')
有时间详细解读下🤦?♂?
|