简介:
itertools——创建高效迭代器的Python模块。
itertools模块可创建的迭代器一般分为三类:
1.无限迭代器
2.终止于最短输入序列的迭代器
3.组合生成器
一.无限迭代器
1 count(),接受两个参数,第一个是开始的数字,第二个是步幅,默认从0开始,用法如下:
importitertools
c= itertools.count(10,2)for i inc:if i > 20:break
print(i)#10 12 14 16 18 20
2 cycle(),接受一个参数,该参数是迭代器对象(列表,字符串等),会循环生成迭代器中的元素:
importitertools
c= itertools.cycle([1,2,3])
i= 1
for j inc:if i > 7:break
print(j)
i+= 1
#1 2 3 1 2 3 1
3 repeat(),接受两个参数,用于生成第一个参数n次:
importitertoolsfor i in itertools.repeat([1,2,3],4):print(i)#[1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3]
二.有限迭代器
1 chain(),接受多个迭代器对象作为参数,并把它们连接起来chain('abc', [1, 2, 3])
2 compress(data, selectors), 根据后面的参数过滤前面的参数,两个参数都需要是迭代器对象
importitertools
a= [1,2,3,4]
b= 'abc'c=itertools.compress(a,b)for i inc:print(i)#1 2 3
3 dropwhile(pre,iterable),pre参数是一个函数,当pre(i)是Ture是,返回该项以及后面所有项
4 groupby(iterable[,keyfunc]),其中iterable 是一个可迭代对象,keyfunc 是分组函数,用于对 iterable 的连续项进行分组,
如果不指定,则默认对 iterable 中的连续相同项进行分组,返回一个 (key, sub-iterator) 的迭代器。
5 ifilter(function orNone,sequence),将 iterable 中 function(item) 为 True 的元素组成一个迭代器返回,
如果 function 是 None,则返回 iterable 中所有计算为 True 的项
6 tee(iterable[,n]),tee 用于从 iterable 创建 n 个独立的迭代器,以元组的形式返回,n 的默认值是 2。
importitertoolsfor i in itertools.tee('abc',5):print(list(i))
三.组合生成器
1 permutations(iterable[,r]),用于生成一个排列,r是生成排列的元素长度,不指定则为默认长度
1 print list(it.permutations('abc'))2 print list(it.permutations('abc', 2))3 #[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]
4 #[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
2 combinations(iterable,r), 求序列的组合,其中,r 指定生成组合的元素的长度,是必需的参数
3 combinations_with_replacement(iterable, r),生成的组合包含自身元素
1 print list(it.combinations_with_replacement('abc', 2))2 #[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]