繁体   English   中英

如何从python中的列表中获取所有可能的组合以允许重复

[英]How to get all possible combinations from a list in python allowing repetition

我有一个类似[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()并改变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)]

手动快速解决方案。 如果您关心性能,则可能应该使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM