问题
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