如何使用此顺序生成python中的所有组合?

时间:2015-06-08 17:57:33

标签: python

我有两个整数nm。我需要使用此顺序生成所有可能的组合:

For n = 3 and m = 4, 
combinations = [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 1, 3], [0, 2, 0], [0, 2, 1], [0, 2, 2], [0, 2, 3], [0, 3, 0], [0, 3, 1], ...]

我可以这样做:

combinations = []
for i in [0, 1, 2, 3]:
    for j in [0, 1, 2, 3]:
        for k in [0, 1, 2, 3]:
            combinations.append([i, j, k])

我有三个for循环,因为n = 3我在每个循环中都有[0, 1, 2, 3]因为m = 4

有关mn的更一般值,怎么办呢?

combinations = []
for i in range(m):
    for j in range(m):
        for k in range(m):
            for l in range(m):
                ... # n loops :(
                   combinations.append([i, j, k, l, ...])

1 个答案:

答案 0 :(得分:0)

itertools.combinbin将会这样做。

import itertools

my_list = [1, 2, 3, 4, 5]
for num in range(0, len(my_list)+1):
  for out in itertools.combinations(my_list, num):
     print(out)