list= [1,2,3,4]it =iter(list)print(next(it))>>>1print(next(it))>>>2list=[1,2,3,4]it =iter(list)# 创建迭代器对象for x in it:print (x, end=" ")输出:1234import sys # 引入 sys 模块list=[1,2,3,4]it =iter(list)# 创建迭代器对象whileTrue:try:print (next(it))exceptStopIteration: sys.exit()
生成无限序列:
>>>from itertools import cycle>>> col =cycle(['red', 'yellow', 'blue'])>>> col<itertools.cycle object at 0x7f060aeeb438>>>>next(col)'red'>>>next(col)'yellow'>>>next(col)'blue'>>>next(col)'red'>>>next(col)'yellow'>>>next(col)'blue'
由无限序列截取有限序列:
>>>from itertools import islice>>> co =cycle(['red', 'yellow', 'blue'])>>> lim =islice(co, 0, 5)>>>for x in lim:... print(x, end=' ')... red yellow blue red yellow
以斐波那契数列定义迭代器:
classFib:def__init__(self): self.prev =0 self.curr =1def__iter__(self):return selfdef__next__(self): value = self.curr self.curr += self.prev self.prev = valuereturn value>>> f =Fib()>>>list(islice(f, 0, 10))[1,1,2,3,5,8,13,21,34,55]
defsomething(): result = []for ... in ...: result.append(x)return result## 转换成生成器函数defiter_something():for ... in ...:yield x
5.生成器表达式
生成器表达式是以列表推导式的方式建立生成器的版本,但是返回的是一个生成器对象
>>> a = (a**2for a inrange(10))>>> a<generator object<genexpr> at 0x7f060c5a17d8>>>> a = (a**3for a inrange(10))>>> a<generator object<genexpr> at 0x7f0607ea83b8>>>> a = (a for a inrange(10))>>> a<generator object<genexpr> at 0x7f060c5a17d8>>>> a = [a**3for a inrange(10)]>>> a[0,1,8,27,64,125,216,343,512,729]>>> b =tuple(a)>>> b(0,1,8,27,64,125,216,343,512,729)