Create list combinations, all with the same length

So, if you use this, you will get possible list combinations

stuff = [1, 2, 3]
for L in range(0, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        print(subset)

And the result

()
(1)
(2)
(3)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)

Is there any way to change this so that the result is

(0, 0, 0)
(1, 0, 0)
(0, 2, 0)
(0, 0, 3)
(1, 2, 0)
(1, 0, 3)
(0, 2, 3)
(1, 2, 3)

or other code that will do this?

+4
source share
1 answer

If the order of the output does not matter, you can put the elements on stuffinto lists of length 2, where the first number is 0, and use itertools.product:

>>> from itertools import product
>>> stuff = [1, 2, 3]
>>> list(product(*([0, x] for x in stuff)))
[(0, 0, 0), (0, 0, 3), (0, 2, 0), (0, 2, 3), (1, 0, 0), (1, 0, 3), (1, 2, 0), (1, 2, 3)]
+6
source

Source: https://habr.com/ru/post/1663375/


All Articles