Skip to main content
 首页 » 编程设计

Python:如何从一系列数字范围创建组合列表

2025年05月04日8me-sa

对于长度为n的数值列表,e。 G。 [1, 3, 1, 2, ...],我想创建一个列表,其中包含 range[x+1] 中所有可能的值组合列表> 其中 x 是列表中的值。输出可能看起来像这样:

for list[1, 3, 2] return all possible lists of range[x+1] values: 
    # the sequence of the list is unimportant 
[ 
[0,0,0],[1,0,0],[0,1,0],[0,2,0],[0,3,0],[0,0,1],[0,0,2],[1,1,0], 
[1,2,0],[1,3,0],[1,0,1],[1,0,2],[0,1,1],[0,2,1],[0,3,1],[0,1,2], 
[0,2,2],[0,3,2],[1,1,1],[1,2,1],[1,3,1],[1,1,2],[1,2,2],[1,3,2] 
] 

所以在这个例子中,我正在寻找 [e1, e2, e3] 的所有变体,来自 e1 in [0,1],e2 in [0,1,2,3 ] 和 [0,1,2] 中的 e3

请您参考如下方法:

将 itertools.product 与动态指定的迭代器列表一起使用:

vals = [1,3,2] 
for item in itertools.product(*[range(x+1) for x in vals]): 
    print item 

输出:

(0, 0, 0) 
(0, 0, 1) 
(0, 0, 2) 
(0, 1, 0) 
(0, 1, 1) 
(0, 1, 2) 
(0, 2, 0) 
(0, 2, 1) 
(0, 2, 2) 
(0, 3, 0) 
(0, 3, 1) 
(0, 3, 2) 
(1, 0, 0) 
(1, 0, 1) 
(1, 0, 2) 
(1, 1, 0) 
(1, 1, 1) 
(1, 1, 2) 
(1, 2, 0) 
(1, 2, 1) 
(1, 2, 2) 
(1, 3, 0) 
(1, 3, 1) 
(1, 3, 2)