## Python生成器和迭代器

1、什么是生成器

>>> a=[i*i for i in range(10)]
>> a
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

2、生成器的特点

>>> a=(i*i for i in range(10))
>>> a
<generator object <genexpr> at 0x00000224FFB4DB48>

>>> next(a)
0
>>> next(a)
1
>>> next(a)
4
>>> next(a)
9
>>> next(a)
16
>>> next(a)
25

>>> a=[i*i for i in range(10)]
>>> for i in a:
print(i, end=' ')
>>> 0 1 4 9 16 25 36 49 64 81

def gen_squares(num):
for x in range(num):
print("x0=",x)
yield x ** 2
print("x1=",x)

for i in gen_squares(5):
print(i)

x0= 0
0
x1= 0
x0= 1
1
x1= 1
x0= 2
4
x1= 2
x0= 3
9
x1= 3
x0= 4
16
x1= 4

for i in gen_squares(5):
print(i)
if i==1:
break

x0= 0
0
x1= 0
x0= 1
1

python使用生成器对延迟操作提供了支持，需要时才计算，不提前计算，这种做法节约内存空间，但是需要一直调用计算过程，可以说是时间换空间吧。

3、什么是迭代器

>>> a=[1,2,3,4]
>>> it = a.__iter__()
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
4
>>> next(it)
Traceback (most recent call last):
File "<pyshell#547>", line 1, in <module>
next(it)
StopIteration

4、实现迭代对象

class square:
def __init__(self, n):
self.prev = 0
self.curr = 0
self.n = n

def __iter__(self):
return self

def __next__(self):
if(self.curr < self.n):
self.prv = self.curr * self.curr
self.curr+=1
return self.prv
else:
raise StopIteration

a = square(10)
for i in a:
print(i)
print("\r\n-------\r\n")
b = square(5)
for i in b:
print(i)

==================== RESTART: C:/Users/plu/my_python/t1.py ====================
0
1
4
9
16
25
36
49
64
81

-------

0
1
4
9
16
>>>

posted on 2020-04-04 22:25  啊哈彭  阅读(355)  评论(0编辑  收藏