Python中的笛卡尔乘积(任意维度)

现在的需求是,有若干个List,假设2个:

[1, 3, 5]

[4, 6]

我们要输出(1, 4), (1, 6), (3, 4), (3, 6), (5, 4), (5, 6)

Python中直接提供了笛卡尔乘积,很给力:

a = [1, 3, 5]
b = [4, 6]
import itertools
for x in itertools.product(a, b):
	print x
(1, 4)
(1, 6)
(3, 4)
(3, 6)
(5, 4)
(5, 6)

而在实际中的问题是,我们要对任意维度(任意个list)之间做笛卡尔乘积。

做法是把要笛卡尔的X个list包装起来,然后加星号,如下:

list = [a, b]
for x in itertools.product(*list):
    print x
(1, 4)
(1, 6)
(3, 4)
(3, 6)
(5, 4)
(5, 6)

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *