list = [1, 2, 3, 4]
it = iter(list)
print(next(it))
>>> 1
print(next(it))
>>>2
list=[1,2,3,4]
it = iter(list) # 创建迭代器对象
for x in it:
print (x, end=" ")
输出:
1 2 3 4
import sys # 引入 sys 模块
list=[1,2,3,4]
it = iter(list) # 创建迭代器对象
while True:
try:
print (next(it))
except StopIteration:
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
以斐波那契数列定义迭代器:
class Fib:
def __init__(self):
self.prev = 0
self.curr = 1
def __iter__(self):
return self
def __next__(self):
value = self.curr
self.curr += self.prev
self.prev = value
return value
>>> f = Fib()
>>> list(islice(f, 0, 10))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
def something():
result = []
for ... in ...:
result.append(x)
return result
## 转换成生成器函数
def iter_something():
for ... in ...:
yield x
5.生成器表达式
生成器表达式是以列表推导式的方式建立生成器的版本,但是返回的是一个生成器对象
>>> a = (a**2 for a in range(10))
>>> a
<generator object <genexpr> at 0x7f060c5a17d8>
>>> a = (a**3 for a in range(10))
>>> a
<generator object <genexpr> at 0x7f0607ea83b8>
>>> a = (a for a in range(10))
>>> a
<generator object <genexpr> at 0x7f060c5a17d8>
>>> a = [a**3 for a in range(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)