CWYAlpha

Just another WordPress.com site

Thought this was cool: Python中的笛卡尔乘积(任意维度)

leave a comment »


现在的需求是,有若干个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)

 

 

 

 
from 四号程序员四号程序员: http://www.coder4.com/archives/3615

Written by cwyalpha

九月 5, 2012 在 4:39 上午

发表在 Uncategorized

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: