所谓迭代器,就是提供next(),而不是通过下标的索引来计数。当在一个循环机制中需要下一项时,调用迭代器的next 方法即可获得它。条目全部取出后,会引发一个StopIteration异常,这并不表示错误的发生,而是告诉外部调用者迭代完成。
python中内置的iter()函数可以创造一个迭代器,举例如下:
>>> list=[23,'fg',44]
>>> i=iter(list)
>>> i.next()
23
>>> i.next()
'fg'
>>> i.next()
44
上面是python的2.7版本下的运行情况,貌似python3.7中做了点修改:
>>> list=[123,'x','mm','gg']
>>> i = iter(list)
>>> i.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list_iterator' object has no attribute 'next'
但iter()的next方法是迭代器中不可少的:
>>> next(i)
'x'
>>> next(i)
'mm'
>>> next(i)
'gg'
>>> next(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
在循环中就能有所体现:
it = iter([1, 2, 3, 4, 5])
while True:
try:
x = next(it)
print(x)
except StopIteration:
break
1
2
3
4
5
python专门有一个迭代器模块:itertools,itertools是python内置的模块,使用简单且功能强大,汇总整理下:
Iterator |
Arguments |
Results |
Example |
---|---|---|---|
|
p [,func] |
p0, p0+p1, p0+p1+p2, ... |
|
|
p, q, ... |
p0, p1, ... plast, q0, q1, ... |
|
|
iterable |
p0, p1, ... plast, q0, q1, ... |
|
|
data, selectors |
(d[0] if s[0]), (d[1] if s[1]), ... |
|
|
pred, seq |
seq[n], seq[n+1], starting when pred fails |
|
|
pred, seq |
elements of seq where pred(elem) is false |
|
|
iterable[, keyfunc] |
sub-iterators grouped by value of keyfunc(v) |
|
|
seq, [start,] stop [, step] |
elements from seq[start:stop:step] |
|
|
func, seq |
func(*seq[0]), func(*seq[1]), ... |
|
|
pred, seq |
seq[0], seq[1], until pred fails |
|
|
it, n |
it1, it2, ... itn splits one iterator into n |
|
|
p, q, ... |
(p[0], q[0]), (p[1], q[1]), ... |
|