使用Python生成迭代的二维数组

时间:2013-10-11 08:56:20

标签: python list

例如,我有以下二维数组

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

提前致谢!

3 个答案:

答案 0 :(得分: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]]

答案 1 :(得分: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)]

答案 2 :(得分:0)

看看itertools模块。 itertools.product函数可以满足您的需求, 除了你可能想要反转输入顺序。