itertools,顾名思义,用作迭代的工具,它不会直接返回一个序列,而是返回一个可迭代的对象,用于 for 循环迭代取出,或者 list comprehension。
1. permutations vs combinations
也即排列是组合的 k! ,当 k=2 时,排列是组合的 2 倍;
也即是数学(组合数学)上的排列组合,permutation 对顺序敏感({1, 2}, {2, 1} 是不同的排列),combination 对顺序不敏感({1, 2, 3}, {1, 3, 2}, … 都是相同的组合)。
(1)实现 C23=3 (组合 3 者之中的两个)
>>> from itertools import combinations, permutations >>> seq = ['r', 'g', 'b'] >>> for c in combinations(seq, 2): print(c) ('r', 'g') ('r', 'b') ('g', 'b')
(2)实现 A23=6 (排列三者之中的两个)
>>> from itertools import combinations, permutations >>> seq = ['r', 'g', 'b'] >>> for c in permutations(seq, 2): print(c) ('r', 'g') ('r', 'b') ('g', 'r') ('g', 'b') ('b', 'r') ('b', 'g')
注意,permutations 方法并不去除重复项:
>> list(permutations([1, 1, 2]))
[(1, 1, 2), (1, 2, 1), (1, 1, 2), (1, 2, 1), (2, 1, 1), (2, 1, 1)]
>> set(permutations([1, 1, 2]))
{(1, 1, 2), (1, 2, 1), (2, 1, 1)}
1,1,2 三个数字的排列数应当为: A33A22=3
2. chain
顾名思义,连接;
>> chain([1, 2], [3, 4])
<itertools.chain at 0x3ddf278>
>> list(chain([1, 2], [3, 4]))
[1, 2, 3, 4]
Return a chain object whose .__next__()
method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted;
chain 功能上更多地等价于 list 的 extend 操作,而不是 zip。
chain 基本上实现了:
for iter in xx:
for i in iter:
...