[python] itertools工具箱

python的itertools提供了许多好用的工具, 主要功能是按照一定规则生成迭代器。不知道这个工具箱的话,面对一些场景,我们往往会用多重for循环代替,不仅代码冗长,而且性能低下。
官网是这样介绍这个工具包的

The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python.

意思是,会玩这个工具的话,你的python代码会简洁高效。

常用的迭代器生成工具如下

# 多个可迭代对象合并成一个
import itertools
list(itertools.chain([1, 2], [3, 4]))
# Output
# [1, 2, 3, 4]

# 字符串转变为可迭代对象
list(itertools.islice('ABCDEFG', 2, 4)) 
# ['C', 'D']

# 以下省略 list
# 组合
itertools.permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
itertools.permutations(range(3)) --> 012 021 102 120 201 210 

# 笛卡尔乘积
itertools.product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
itertools.product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 

# 对应位置的乘积
izip([1, 2, 3], ['a', 'b', 'c'])
# Output
# [(1, 'a'),(2, 'b'),(3, 'c')]
# 长度不同,可以给个默认
itertools.zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-

# 重复
itertools.repeat(10, 3) --> 10 10 10 
# 如果不指定参数,则每一次执行,都给出第一个参数,常用来为map,zip提供恒定参数 
list(map(pow, range(10), itertools.repeat(3)))
# [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] 

# 映射
itertools.starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000 

# 压缩
itertools.compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F 

# 数数
itertools.count(10) --> 10 11 12 13 14 ...
itertools.count(2.5, 0.5) -> 2.5 3.0 3.5 ... 

# 循环
itertools.cycle('ABCD') --> A B C D A B C D A B C D ... 

# 过滤
itertools.dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1 
itertools.filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8 

你可能感兴趣的:([python] itertools工具箱)