3.3中itertools.product记录
2021-03-02 本文已影响0人
richybai
itertools.product
用于求多个可迭代对象的笛卡尔积,和嵌套循环等价。
其使用方法如下:
import itertools
itertools.product(*iterables, repeat=1)
*iterables
是多个可迭代对象,repeat
表示重复几次。
product(A, repeat=3)
与product(A, A, A)
等价。
以下为一些实例展示:
A = [0, 1]
>>> for x in itertools.product(A, repeat=3):
... print(x, end=" ")
(0, 0, 0) (0, 0, 1) (0, 1, 0) (0, 1, 1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1)
>>> for x in itertools.product("ABCD", "12"):
... print(x, end=" ")
...
('A', '1') ('A', '2') ('B', '1') ('B', '2') ('C', '1') ('C', '2') ('D', '1') ('D', '2')