简体   繁体   中英

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
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.

Does anyone know how could I get a list with the desired result?

You need itertools.combinations_with_replacement() and vary the 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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