9. itertools模块¶
chain¶
chain()可以把一组迭代对象串联起来,形成一个更大的迭代器
chain(iterobject1,iterobject2,iterobject...)
chain.from_iterable(iterobject)
groupby¶
groupby()把迭代器中相邻的重复元素挑出来放在一起,必须首先保证有序
>>> for key, group in itertools.groupby('AAABBBCCAAA'):
... print(key, list(group))
...
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']
accumulate¶
accumulate(iterable [,func]) 可以计算出一个迭代器,这个迭代器是由特定的二元函数的累计结果生成的,如果不指定的话,默认函数为求和函数。
>>> list(itertools.accumulate([1,2,3,4,5]))
[1, 3, 6, 10, 15]
repeat¶
repeat(elem [,n])是将一个元素重复n遍或者无穷多遍,并返回一个迭代器。 但是需要注意的是,如果elem是可变对象,则改变其中某个值,其余值都会变
>>> list(itertools.repeat(1,3))
[1, 1, 1]
>>> a=list(itertools.repeat([],3))
>>> a
[[], [], []]
>>> a[0].append(1)
>>> a
[[1], [1], [1]]
product¶
product(*iterables, repeat=1) 得到的是可迭代对象的笛卡儿积,*iterables参数表示需要多个可迭代对象。
>>> list(itertools.product([1,2,3], [4,5,6]))
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
permutations¶
permutations(iterable, r=None)返回的是可迭代元素中的一个排列组合,并且是按顺序返回的,且不包含重复的结果。 第 2 个参数默认为None,它表示的是返回元组(tuple) 的长度
>>> list(itertools.permutations('abc'))
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]
>>> list(itertools.permutations('abc', 2))
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
combinations¶
combinations(iterable, r) 返回的是可迭代对象所有的长度为 r 的子序列
>>> list(itertools.combinations('1234', 2))
[('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')]
combinations_with_replacement¶
combinations_with_replacement(iterable, r) 返回一个可与自身重复的元素组合
>>> list(itertools.combinations_with_replacement('1234', 2))
[('1', '1'), ('1', '2'), ('1', '3'), ('1', '4'), ('2', '2'), ('2', '3'), ('2', '4'), ('3', '3'), ('3', '4'), ('4', '4')]
reference:
https://docs.python.org/3.7/library/itertools.html