How to generate list combinations?

2019-01-19 08:49发布

问题:

I want to produce a list of lists that represents all possible combinations of the numbers 0 and 1. The lists have length n.

The output should look like this. For n=1:

[ [0], [1] ]

For n=2:

[ [0,0], [0, 1], [1,0], [1, 1] ]

For n=3:

[ [0,0,0], [0, 0, 1], [0, 1, 1]... [1, 1, 1] ]

I looked at itertools.combinations but this produces tuples, not lists. [0,1] and [1,0] are distinct combinations, whereas there is only one tuple (0,1) (order doesn't matter).

Any hints or suggestions? I have tried some recursive techniques, but I haven't found the solution.

回答1:

You're looking for itertools.product(...).

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

If you want to convert the inner elements to list type, use a list comprehension

>>> [list(elem) for elem in product([1, 0], repeat =2)]
[[1, 1], [1, 0], [0, 1], [0, 0]]

Or by using map()

>>> map(list, product([1, 0], repeat=2))
[[1, 1], [1, 0], [0, 1], [0, 0]]


回答2:

Use itertools.product, assigning the repeat to n.

from itertools import product
list(product([0,1], repeat=n))

Demo:

>>> list(product([0,1], repeat=2))
[(0, 0), (0, 1), (1, 0), (1, 1)]
>>> list(product([0,1], repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]


回答3:

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

To get list of list, you can do:

>>> map(list, list(product([0, 1], repeat=2)))
[[0, 0], [0, 1], [1, 0], [1, 1]]


回答4:

Just to add a bit of diversity, here's another way of achieving this:

>>> [map(int, format(i, "03b")) for i in range(8)]
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]