python中迭代器的使用是最广泛的,凡是使用for语句,其本质都是迭代器的应用。
从代码角度看,迭代器是实现了迭代器协议的对象或类。迭代器协议方法主要是两个:
- __iter__()
- __next__()
__iter__()方法返回对象本身,他是for语句使用迭代器的要求。
__next__()方法用于返回容器中下一个元素或者数据。当容器中的数据用尽时,引发StopIteration异常。
任何一个类,只要实现了或者具有这两个方法,就可以称其为迭代器,也可以说是可迭代的。
内置迭代器工具
Python语言中,已经内建了一个用于产生迭代器的函数iter(),另外标准库的itertools模块中还有丰富的迭代器工具。
1.内建迭代器函数
内建的iter()函数有两种使用方法,原型如下:
iter(iterable) 参数iterable为可迭代类型
iter(callable,sentinel) 参数callable为可调用类型,参数sentinel称为‘哨兵’,即当第一个参数调用返回值等于第二个参数的值时,迭代或遍历停止。
2.itertools中常用的工具函数
itertools中提供了近二十种迭代器函数,主要分为三类
无限迭代器
count(start,[step]) # 从start开始,以step为步进行技术迭代
import itertools
for i in itertools.count(1,3):
print(i)
if i>=10:
break
1
4
7
10
cycle(seq) # 无线循环迭代seq
x=0
for i in itertools.cycle(['a','b']):
print(i)
x+=1
if x>=6:
break
a
b
a
b
a
b
repeat(elem,[n]) # 循环迭代elem
list(itertools.repeat(3,6))
[3, 3, 3, 3, 3, 3]
迭代短序列:
chain(p,q,...) 链接迭代,将p,q连接起来迭代,就像从一个序列中迭代
list(itertools.chain([1,2],[8,9]))
[1, 2, 8, 9]
compress(data,selectors) 依据selectors中的值选择迭代data序列中的值
list(itertools.compress([1,2,3,4,5,6,7,8,9,10],[1,'','2',None,{'a':3},{4},[],{},5,0]))
[1, 3, 5, 6, 9]
dropwhile(pred,seq) 当pred对序列元素处理结果为假时开始迭代seq后所有值
list(itertools.dropwhile(lambda x:x>6,[8,9,1,2,6,7]))
[1, 2, 6, 7]
filterfalse(pred,seq) 当pred处理为假的元素
list(itertools.filterfalse(lambda x:x>6,[8,9,1,2,6,7]))
[1, 2, 6]
takewhile(pred,seq) 与dropwhile相反
list(itertools.takewhile(lambda x:x>6,[8,9,1,2,6,7]))
[8, 9]
tee(it,n) 将it重复n次进行迭代
for its in itertools.tee([1,2,3],3):
for i in its:
print(i)
1
2
3
1
2
3
1
2
3
zip_longest(p,q,...)
组合迭代器
product(p,q,...[,n]) 迭代排列出所有的排列
list(itertools.product('abcd', '123'))
[('a', '1'), ('a', '2'), ('a', '3'), ('b', '1'), ('b', '2'), ('b', '3'), ('c', '1'), ('c', '2'), ('c', '3'), ('d', '1'), ('d', '2'), ('d', '3')]
permutations(p,r) 迭代序列中r个元素的排列
list(itertools.permutations('abcd', 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('d', 'a'), ('d', 'b'), ('d', 'c')]
combinations(p,r) 迭代序列中r个元素的组合
list(itertools.combinations('abcd', 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]