【问题标题】:Python permutations of two integers of given length [duplicate]给定长度的两个整数的Python排列[重复]
【发布时间】:2017-06-20 17:33:10
【问题描述】:

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

【问题讨论】:

  • 谢谢,这正是我所需要的。我不知道为什么它没有出现在我的搜索中。

标签: python-3.x permutation


【解决方案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]

【讨论】:

    【解决方案2】:
    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 2011-07-20
      • 1970-01-01
      相关资源
      最近更新 更多