2013-10-11 73 views
0

例如我已經通過使用列表解析以下2-d陣列生成2-d陣列使用Python

t = [[1,2,3], 
    [4,5], 
    [6,7]] 

我得到

>>> [[x, y, z] for x in t[2] for y in t[1] for z in t[0]] 
[[6, 4, 1], 
[6, 4, 2], 
[6, 4, 3], 
[6, 5, 1], 
[6, 5, 2], 
[6, 5, 3], 
[7, 4, 1], 
[7, 4, 2], 
[7, 4, 3], 
[7, 5, 1], 
[7, 5, 2], 
[7, 5, 3]] 

但如何,如果輸入具有更多的迭代比3個列表?我的意思是,我不想硬編碼t [2]等等。我想以包含任意數量的列表作爲輸入的t。無論如何,使用列表解析來做到這一點?

提前致謝!

+0

我會看看[itertools](http://docs.python.org/2/library/itertools.html) – cenna75

回答

4

使用itertools.product

>>> import itertools 
>>> t = [[1,2,3], [4,5], [6,7]] 
>>> [x for x in itertools.product(*t[::-1])] 
[(6, 4, 1), 
(6, 4, 2), 
(6, 4, 3), 
(6, 5, 1), 
(6, 5, 2), 
(6, 5, 3), 
(7, 4, 1), 
(7, 4, 2), 
(7, 4, 3), 
(7, 5, 1), 
(7, 5, 2), 
(7, 5, 3)] 
>>> [list(x) for x in itertools.product(*t[::-1])] 
[[6, 4, 1], 
[6, 4, 2], 
[6, 4, 3], 
[6, 5, 1], 
[6, 5, 2], 
[6, 5, 3], 
[7, 4, 1], 
[7, 4, 2], 
[7, 4, 3], 
[7, 5, 1], 
[7, 5, 2], 
[7, 5, 3]] 
+0

你打我吧! = D – justhalf

2

使用itertools.product

In [1]: import itertools 

In [2]: t = [[1,2,3], [4,5], [6,7]] 

In [3]: list(itertools.product(*t[::-1])) 
Out[3]: 
[(6, 4, 1), 
(6, 4, 2), 
(6, 4, 3), 
(6, 5, 1), 
(6, 5, 2), 
(6, 5, 3), 
(7, 4, 1), 
(7, 4, 2), 
(7, 4, 3), 
(7, 5, 1), 
(7, 5, 2), 
(7, 5, 3)] 
+0

這很酷!謝謝! –

0

看一看itertools模塊裏。 itertools.product函數做你想要的, ,除了你可能想要扭轉輸入順序。