[英]How to get all possible combinations from a list in python allowing repetition
I have a list like [1,2,3]
and I want to get the following result: 我有一个类似
[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
I've tried using itertools
, but I only get the combinations without repetition. 我已经尝试过使用
itertools
,但是我只能重复使用这些组合。
Does anyone know how could I get a list with the desired result? 有谁知道我怎么得到期望结果的清单?
You need itertools.combinations_with_replacement()
and vary the r
. 您需要
itertools.combinations_with_replacement()
并改变r
。 this isn't in your order as it is unclear if this is a requirement, eg: 这不是您的订单,因为尚不清楚这是否是必需条件,例如:
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)]
A quick solution by hand. 手动快速解决方案。 If you care about performance you should probably stick with
itertools
. 如果您关心性能,则可能应该使用
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.