Skip to main content
 首页 » 编程设计

python之在python中生成数组列的所有可能组合

2025年05月04日16luoye11

比如我有这样的数组

[ 
  [1,2,3], 
  [4], 
  [5,6], 
] 

我想从上面的列表中生成所有组合,如果它应该看起来像这样的话。

[1, 4, 5] 
[1, 4, 6] 
[2, 4, 5] 
[2, 4, 6] 
[3, 4, 5] 
[3, 4, 6] 

请您参考如下方法:

听起来像你想要的product来自内置 itertools图书馆

>>> import itertools 
>>> list(itertools.product([1, 2, 3], [4], [5, 6])) 
[(1, 4, 5), (1, 4, 6), (2, 4, 5), (2, 4, 6), (3, 4, 5), (3, 4, 6)] 
>>> 
>>> columns = [[1,2,3], 
               [4], 
               [5,6]] 
>>> list(itertools.product(*columns)) 
[(1, 4, 5), (1, 4, 6), (2, 4, 5), (2, 4, 6), (3, 4, 5), (3, 4, 6)]