Get a list of N items with K-selections for each item?

For example, if I have a selection set K

K = ['a','b','c']

      

and length N

N = 4

      

I want to return everything I can:

['a','a','a','a']
['a','a','a','b']
['a','a','a','c']
['a','a','b','a']
...
['c','c','c','c']

      

I can do it with recursion, but it is not interesting. Is there a more pythonic way?

+3


source to share


1 answer


This can be done with itertools

.

>>> K = ['a','b','c']
>>> import itertools
>>> N = 4
>>> i = itertools.product(K,repeat = N)
>>> l = [a for a in i]
>>> l[:3]
[('a', 'a', 'a', 'a'), ('a', 'a', 'a', 'b'), ('a', 'a', 'a', 'c')]

      



EDIT: I figured out what you really want product

, not combinations_with_replacement

. Updated code.

+7


source







All Articles