【问题标题】:How to get all possible combinations from a list in python allowing repetition如何从允许重复的python列表中获取所有可能的组合
【发布时间】:2018-05-31 11:45:35
【问题描述】:

我有一个类似[1,2,3] 的列表,我想得到以下结果:

1
1,1
1,1,1
1,2
1,2,1
1,2,2
1,2,3
1,2
1,3
1,3,3
2,1,2
2,2,1
3,1,1
etc

我尝试过使用itertools,但我只得到没有重复的组合。

有谁知道我怎样才能获得具有所需结果的列表?

【问题讨论】:

  • 你试过itertools.combinations_with_replacement()吗?

标签: python python-3.x list combinations itertools


【解决方案1】:

您需要itertools.combinations_with_replacement() 并更改r。这不在您的订单中,因为不清楚这是否是要求,例如:

In []:
from itertools import combinations_with_replacement as cwr
nums = [1, 2, 3]
[x for n in range(1, len(nums)+1) for x in cwr(nums, r=n)]

Out[]:
[(1,), (2,), (3,), (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3), (1, 1, 1), (1, 1, 2), 
 (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)]

In []:
from itertools import product
[x for n in range(1, len(nums)+1) for x in product(nums, repeat=n)]

Out[]:
[(1,), (2,), (3,), (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3), 
 (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), 
 (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), 
 (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), 
 (3, 3, 1), (3, 3, 2), (3, 3, 3)]

【讨论】:

  • 谢谢。我在问这个问题时犯了一个错误,并没有表明还需要像 2,1,1 这样的组合,其中第一个数字可以大于其他数字。我不知道这是否可以通过 itertools 实现,但 Yakym 提供的答案满足了我的需要。
  • 只需使用itertools.product(),已添加。
【解决方案2】:

手动快速解决方案。如果您关心性能,您可能应该坚持使用itertools

def all_combs(xs):
    res = []
    buf = [[]]
    lst = [[x] for x in xs]
    for _ in xs:
        buf = [r + l for r in buf for l in lst]
        res.extend(buf)

    return res

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多