【问题标题】:How to get every possible combination of list integers?如何获得列表整数的所有可能组合?
【发布时间】:2021-07-24 08:44:08
【问题描述】:

我有一个列表L = [3, 4, 1, 5, 9],我想通过使用列表L 中的数字来获取所有可能的数字。我的意思是,我想得到这样的输出:[3, 4, 1, 5, 9, 34, . . . . , 91, 953, ... ,41593, ... etc.] 我正在使用此代码:

from itertools import combinations
possible_numbers = []

output = (sum([list(map(list, combinations(L, i))) for i in range(len(L) + 1)], []))
output.pop(0)

for x in output:
    strings = [str(integer) for integer in x]
    a_string = "".join(strings)
    possible_numbers.append(int(a_string))
    print(output)

但我得到了这种类型的输出:

[3,4,1,5,9,34,31,35,39, 4145,49,15,19,59,341,345,349,315,319,359,415,419,459,159,3415,3419,3459,3159,4159,34159]

显然这不是我想要的,因为列表L 可以形成更多可能的组合。谁能帮忙。

【问题讨论】:

  • 也许你应该用正常的for 循环将output = (sum ....) 行重写为几行。这对我来说太复杂了,我无法理解它是否正确(显然,对你来说也是如此)。
  • 使用 permutations 而不是 combinations (然后我在列表中得到 325 个数字)
  • 这能回答你的问题吗? Generating all combinations of a list in python
  • @mkrieger1 不,在发布这个问题之前,我访问了那个答案,但它对我不起作用,因为我想要一个数字列表,而不是整数组合。

标签: python list


【解决方案1】:

试试itertools.permutations:

from itertools import permutations

L = [3, 4, 1, 5, 9]

for i in range(1, len(L) + 1):
    for p in permutations(L, i):
        print(int("".join(map(str, p))))

打印:

3
4
1
5
9
34
31
35

...

95431
95413
95134
95143

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2019-10-25
    • 2013-02-12
    • 1970-01-01
    相关资源
    最近更新 更多