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

Col*_*ole 1 python

对于n长度的数值列表,例如[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]
]
Run Code Online (Sandbox Code Playgroud)

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

box*_*ein 5

Python的itertools模块有一个工具,可以满足您的需求:

import itertools
p = itertools.permutations([0, 1, 2, 3])
p_as_list = list(p)
Run Code Online (Sandbox Code Playgroud)

编辑:由于您的需求非常具体,您可以从拥有自己的功能中获益,这个功能与此相似:(注意我还没有完成实现,也许有人可能会对此进行改进):

def magic_permutations (*args):
    lists = []
    larg = len(args)
    for i in range(larg):
        lists.append([])
    i = 0
    for nums in args: 
        for num in nums:
            if i >= larg:
                i = 0
            lists[i].append(num)
            i += 1
    return lists
Run Code Online (Sandbox Code Playgroud)

编辑:我第一次误解了你的问题,所以我会为此道歉.不过我会留下这个.

  • 没有给出理想的答案.如果`p = itertools.permutations([1,3,2])`,`len(list(p))`只有6. (2认同)

nne*_*neo 5

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

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

输出:

(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)
Run Code Online (Sandbox Code Playgroud)