generating binary numbers of size n as tuples : itertools.product(*[(0, 1)] * n)

拜拜、爱过 提交于 2019-12-11 11:33:25

问题


  • I just found this instruction

    itertools.product(*[(0, 1)] * n)
    

    posted by PAG.

    Can someone explain how it works?

  • I am trying to find a way of doing permutations without repetition of n tuples in 3 bags and I only can use itertools if I want. Thanks

回答1:


[(0, 1)] is a list of a single tuple of the numbers 0 and 1.

[(0, 1)] * n duplicates the tuple inside of the list, so we get

[(0, 1), (0, 1), ..., (0, 1), (0, 1)]

Then, if we look at the itertools.product function, we want to pass in each of those tuples as single arguments. So, we use the *-operator to unpack our list into arguments to the itertools.product function. So, our function is equivalent to:

itertools.product((0, 1), (0, 1), ..., (0, 1), (0, 1))

which computes all permutations of the n 0s and 1s.

Note that itertools.product takes a repeat parameter, which should be used to do this sort of thing:

itertools.product((0, 1), repeat=n)

To do permutations, you can use the itertools.permutations function:

def pick_into_three_bags(n):
    return itertools.permutations(range(n), 3)


来源:https://stackoverflow.com/questions/16330105/generating-binary-numbers-of-size-n-as-tuples-itertools-product0-1-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!