python标准库itertools模块使用方法

简介

官方描述:functional tools for creating and using iterators.即用于创建高效迭代器的函数。

itertools.chain(*iterable)

将多个序列作为一个单独的序列返回。例如:

import itertools
for each in itertools.chain(‘i’, ‘love’, ‘python’):
print each

输出:

i
l
o
v
e
p
y
t
h
o
nitertools.combinations(iterable, r)

返回指定长度的”组合”例如:

import itertools
for each in itertools.combinations(‘abc’, 2):
print each

输出:

(‘a’, ‘b’)
(‘a’, ‘c’)
(‘b’, ‘c’)itertools.combinations_with_replacement(iterable, r)

返回指定长度的“组合”,组合内元素可重复例如:

import itertools
for each in itertools.combinations_with_replacement(‘abc’, 2):
print each

输出:

(‘a’, ‘a’)
(‘a’, ‘b’)
(‘a’, ‘c’)
(‘b’, ‘b’)
(‘b’, ‘c’)
(‘c’, ‘c’)itertools.product(*iterable[,repeat])

返回指定长度的所有组合,可理解为笛卡尔乘积例如:

import itertools
for each in itertools.product(‘abc’, repeat=2):
print each

(‘a’, ‘a’)(‘a’, ‘b’)(‘a’, ‘c’)(‘b’, ‘a’)(‘b’, ‘b’)(‘b’, ‘c’)(‘c’, ‘a’)(‘c’, ‘b’)(‘c’, ‘c’)

itertools.premutations(iteravle[,r])

返回长度为r的排列例如:

import itertools
for value in itertools.permutations(‘abc’, 2):
print value

输出:

(‘a’, ‘b’)
(‘a’, ‘c’)
(‘b’, ‘a’)
(‘b’, ‘c’)
(‘c’, ‘a’)
(‘c’, ‘b’)itertools.compress(data,selector)

返回selector为true的data对应元素例如:

import itertools
for each in itertools.compress(‘abcd’, [1, 0, 1, 0]):
print each

输出:

a
citertools.count(start=0,step=1)

返回以start开始,step递增的序列,无限递增例如:

import itertools
for each in itertools.count(start=0, step=2):
print each

输出:

1
2
3
.
.itertools.cycle(iterable)

将迭代器进行无限迭代例如:

import itertools
for each in itertools.cycle(‘ab’):
print each

输出:

a
b
a
b
.
.itertools.dropwhile(predicate, iterable)

直到predicate为真,就返回iterable后续数据, 否则drop掉例如:

import itertools
for each in itertools.dropwhile(lambda x: x

Posted in 未分类