python的itertools.product()函数

itertools是一个提供迭代器的库。itertools.product()函数返回多个可迭代对象的笛卡尔积。

示例1:两个列表的笛卡尔积

它的等价循环如下:
(x,y) for x in A for y in B

from itertools import *
for i in product([7,8,9],[1,2,3]):
	print (i)

输出:

(7, 1)
(7, 2)
(7, 3)
(8, 1)
(8, 2)
(8, 3)
(9, 1)
(9, 2)
(9, 3)

示例2:

共3个位置, 每个位置可能出现0或者1, 列出所有可能

for i in product([0,1],repeat=3):
	print (i)

输出:

(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)

猜你喜欢

转载自blog.csdn.net/qq_45268474/article/details/108504294