这里记录下itertools中常用的排列,组合,笛卡尔积等方法
- 排列 permutations
>>> from itertools import permutations
>>> t = permutations([1,2,3],2)
>>> list(t)
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
>>> t = permutations([1,2,3],3)
>>> list(t)
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
- 组合 combinations
>>> from itertools import combinations
>>> t = combinations([1,2,3],2)#第一个参数是序列,第二个参数是放回几个元素的组合
>>> list(t)
[(1, 2), (1, 3), (2, 3)]
>>> t = combinations([1,2,3],3)
>>> list(t)
[(1, 2, 3)]
>>> t = combinations([1,2,3],1)
>>> list(t)
[(1,), (2,), (3,)]
>>> t = combinations([1,2,3],0)
>>> list(t)
[()]
>>> t = combinations([1,2,3],-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: r must be non-negative
- 笛卡尔积 product
>>> from itertools import product
>>> t = product([1,2,3],[4,5])
>>> list(t)
[(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
>>> t = product([1,2,3],(4,5))#传入元组
>>> list(t)
[(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
>>> t = product('hello','world')#传入字符串
>>> list(t)
[('h', 'w'), ('h', 'o'), ('h', 'r'), ('h', 'l'), ('h', 'd'), ('e', 'w'), ('e', 'o'), ('e', 'r'), ('e', 'l'), ('e', 'd'), ('l', 'w'), ('l', 'o'), ('l', 'r'), ('l', 'l'), ('l', 'd'), ('l', 'w'), ('l', 'o'), ('l', 'r'), ('l', 'l'), ('l', 'd'), ('o', 'w'), ('o', 'o'), ('o', 'r'), ('o', 'l'), ('o', 'd')]
>>> t = product([1,2,3],(4))#两个参数必须是可迭代的
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> t = product([1,2,3],(4,))#此时就不会报错
>>> list(t)
[(1, 4), (2, 4), (3, 4)]
>>> t = product([1,2,3],)#传入一个序列就是分开
>>> list(t)
[(1,), (2,), (3,)]
- 累加 accumulate
>>> from itertools import accumulate
>>> t = accumulate(range(1))
>>> list(t)
[0]
>>> t = accumulate(range(2))
>>> list(t)
[0, 1]
>>> t = accumulate(range(3))
>>> list(t)
[0, 1, 3]
>>> t = accumulate(range(4))
>>> list(t)
[0, 1, 3, 6]
>>> t = accumulate(range(0))
>>> list(t)
[]
##返回值就是传入序列对应位置及前n个元素的和组成的新列表
##例如
##输入
##[1,2,3,4,5]
##返回
##[1,3,6,10,15]
- 连接容器 chain
>>> x = chain(range(3),range(4),range(5))
>>> list(x)
[0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4]