Create a list of combinations

I would like to create a list of numbers with three values ​​and would like to cover every combination from 0 to 3. For example:

0, 0, 0
0, 0, 1
...
1, 0, 3
1, 1, 3

      

before 3, 3, 3

.

Is there a better way to do this than using multiple loops?

Here is the code I used:

for i in range (0, 4):
    for x in range (0, 4):
        for t in range (0, 4):
        assign = [i, x, t]

      

+3


source to share


4 answers


Usually itertools.product

:



list(itertools.product(range(4), repeat=3))

+3


source


You can use itertools.product

:



>>> from itertools import product
>>> list(product({0, 1, 2, 3}, repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (0, 3, 0), (0, 3, 1), (0, 3, 2), (0, 3, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 0), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 0, 3), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 0), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 0), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 0, 0), (3, 0, 1), (3, 0, 2), (3, 0, 3), (3, 1, 0), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 0), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 0), (3, 3, 1), (3, 3, 2), (3, 3, 3)]
>>>

      

+2


source


For this you can use the function itertools.product()

:

from itertools import product

for i, x, t in product(range(4), repeat=3):
    print (i, x, t)

      

Demo:

>>> from itertools import product
>>> for i, x, t in product(range(4), repeat=3):
...     print (i, x, t)
... 
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 0, 3)
(0, 1, 0)
# ... truncated for readability ...
(3, 2, 3)
(3, 3, 0)
(3, 3, 1)
(3, 3, 2)
(3, 3, 3)

      

+2


source


itertools.product()

is a great solution, but if you need a list of lists and not tuples, you can use this:

[ [x,y,z] for x,y,z in itertools.product(range(4), repeat=3)]

      

or an equivalent list comprehension:

[ [x,y,z] for x in range(0,4)
            for y in range(0,4)
                for z in range(0,4)]

      

+1


source







All Articles