# 小白学 Python（21）：生成器基础

## 生成器

list1 = [x*x for x in range(10)]
print(list1)


[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


list2 = [x*x for x in range(1000000000000000000000000)]


Traceback (most recent call last):
File "D:/Development/Projects/python-learning/base-generator/Demo.py", line 3, in <module>
list2 = [x*x for x in range(1000000000000000000000000)]
File "D:/Development/Projects/python-learning/base-generator/Demo.py", line 3, in <listcomp>
list2 = [x*x for x in range(1000000000000000000000000)]
MemoryError


generator1 = (x*x for x in range(1000000000000000000000000))
print(generator1)
print(type(generator1))


<generator object <genexpr> at 0x0000014383E85B48>
<class 'generator'>


generator2 = (x*x for x in range(3))
print(next(generator2))
print(next(generator2))
print(next(generator2))
print(next(generator2))


Traceback (most recent call last):
File "D:/Development/Projects/python-learning/base-generator/Demo.py", line 14, in <module>
print(next(generator2))
StopIteration


generator3 = (x*x for x in range(5))
for index in generator3:
print(index)


0
1
4
9
16


generator 非常的强大，本质上， generator 并不会取存储我们的具体元素，它存储是推算的算法，通过算法来推算出下一个值。

def print_a(max):
i = 0
while i < max:
i += 1
yield i

a = print_a(10)
print(a)
print(type(a))


<generator object print_a at 0x00000278C6AA5CC8>
<class 'generator'>


print(next(a))
print(next(a))
print(next(a))
print(next(a))


1
2
3
4


print(a.__next__())
print(a.__next__())


5
6


def print_b(max):
i = 0
while i < max:
i += 1
args = yield i
print('传入参数为：' + args)

b = print_b(20)
print(next(b))
print(b.send('Python'))


1

2


def print_c():
while True:
print('执行 A ')
yield None
def print_d():
while True:
print('执行 B ')
yield None

c = print_c()
d = print_d()
while True:
c.__next__()
d.__next__()


...

...


## 示例代码

posted @ 2019-11-14 08:45  极客挖掘机  阅读(287)  评论(0编辑  收藏