2012-02-01 79 views
4

可能重复:
Get the cartesian product of a series of lists in PythonPython的笛卡尔乘积

我想弄清楚,我只是不能绕到我的头有些逻辑。说我有以下数据结构:

letters = (
    ('b','c'), 
    ('a','e','ee'), 
    ('d','f'), 
    ('e','y'), 
) 

我怎么会通过这个循环让每一个可能的字符串组合:

bade 
cade 
bede 
cede 
beede 
ceede 
bafe 
cafe 
befe 
cefe 
beefe 
ceefe 
bady 
cady 
bedy 
cedy 
beedy 
ceedy 
bafy 
cafy 
befy 
cefy 
beefy 
ceefy 
+4

您正在寻找对于笛卡尔产品:http://docs.python.org/library/itertools.html#itertools.product – 2012-02-01 18:22:55

回答

6

我会使用itertools.product()

for l in itertools.product(*letters): 
    print ''.join(l) 
+0

字母前使用'*'有什么用途?它有什么作用? – 2015-08-25 09:24:49

+1

参数解包:* [a,b,c]是a,b,c – 2016-10-02 14:31:36