给定长度的两个整数的Python排列

时间:2017-06-20 17:33:10

标签: python-3.x permutation

Python中是否有一种简单的方法可以使用一个或两个整数计算给定长度的所有可能的排列。例如,如果我的整数是1和2并且我想计算长度为3的所有可能的排列,我应该得到(111,112,121,122,211,212,221,222)。我认为itertools.permutations会起作用,但显然长度是>整数,不返回任何项目。

2 个答案:

答案 0 :(得分:1)

如果您正在寻找的只是:

[(1, 1), (1, 2), (2, 1), (2, 2)]

然后看Permutation of x length of 2 characters,这个帖子是重复的。

如果您正在寻找的是

[11, 12, 21, 22]

然后使用:

import itertools as it
print([int(str(i) + str(j)) for i, j in it.product(l, repeat=2)])
[11, 12, 21, 22]

答案 1 :(得分:-1)

import itertools

length = 3
possible_int = [1,2]
all_permutations = []
for i in range(length+1):
    first = [possible_int[0]]*i
    second = [possible_int[1]]*(length-i)
    permutations = [list(x) for x in itertools.permutations(first+second)]
    for element in permutations:
        if element not in all_permutations:
            all_permutations.append(element)

print(all_permutations)