python all possible combinations of 0,1 of length k

前端 未结 1 882
执念已碎
执念已碎 2020-12-19 01:34

I need all possible combinations of 0,1 of length k.

Suppose k=2 I want (0,0), (0,1), (1,0), (1,1)

I have tried different function in it

1条回答
  •  星月不相逢
    2020-12-19 02:23

    itertools.product() takes a repeat keyword argument; set it to k:

    product(range(2), repeat=k)
    

    Demo:

    >>> from itertools import product
    >>> for k in range(2, 5):
    ...     print list(product(range(2), repeat=k))
    ... 
    [(0, 0), (0, 1), (1, 0), (1, 1)]
    [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
    [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]
    

    0 讨论(0)
提交回复
热议问题