0

例如我有以下二维数组

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包含任意数量的列表作为输入。无论如何使用列表推导来做到这一点?

提前致谢!

4

3 回答 3

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]]
于 2013-10-11T09:00:56.050 回答
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)]
于 2013-10-11T09:01:29.530 回答
0

看看 itertools 模块。itertools.product函数做你想做的事,除了你可能想颠倒输入顺序。

于 2013-10-11T09:03:00.703 回答