判断一个对象是否可迭代:
In [6]: from collections import Iterable
In [7]: isinstance([], Iterable)
Out[7]: True
In [8]: isinstance({}, Iterable)
Out[8]: True
In [9]: isinstance("", Iterable)
Out[9]: True
In [10]: isinstance(100, Iterable)
Out[10]: False
迭代器
可以用next()获取下一个值
In [20]: x = (i for i in range(10))
In [21]: next(x)
Out[21]: 0
In [22]: next(x)
Out[22]: 1
In [23]: next(x)
Out[23]: 2
In [24]: next(x)
Out[24]: 3
In [27]: isinstance(x, Iterator)
Out[27]: True
iter() 函数
可以将可迭代对象,变成迭代器:
In [30]: a = [11,22,33]
In [31]: isinstance(a, Iterator)
Out[31]: False
In [32]: iter(a)
Out[32]: <list_iterator at 0x7f0dee3abc50>
In [33]: b = iter(a)
In [34]: isinstance(b, Iterator)
Out[34]: True
In [35]: next(b)
Out[35]: 11
In [36]: next(b)
Out[36]: 22
In [37]: next(b)
Out[37]: 33
包含yield的函数,是生成器
不会结束程序的return,是迭代器,能用next()取下一个值。
In [57]: type(x for x in range(10))
Out[57]: generator
In [59]: def gen(max):
....: n = 0
....: while n<max:
....: yield n
....: n+=1
....:
In [60]: type(gen)
Out[60]: function
In [61]: type(gen(10))
Out[61]: generator
In [63]: for i in gen(10):
....: print(i)
....:
0
1
2
3
4
5
6
7
8
9
相当于:
from collections import Iterator
class Gen(object):
def __init__(self,max):
self.max=max
self.n=0
def __iter__(self):
return self
def __next__(self):
if self.n<self.max:
tmp=self.n
self.n+=1
return tmp
raise StopIteration
print(isinstance(Gen(10), Iterator) )
for i in Gen(10):
print(i, end=' ')
True
0 1 2 3 4 5 6 7 8 9
网友评论