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
0
s and 1
s.
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)