生成大小为n的二进制数作为元组:itertools.product(* [(0,1)] * n) [英] generating binary numbers of size n as tuples : itertools.product(*[(0, 1)] * n)
问题描述
-
我刚刚找到了此说明
I just found this instruction
itertools.product(*[(0, 1)] * n)
由PAG发布.
有人可以解释它的工作原理吗?
Can someone explain how it works?
推荐答案
[(0, 1)]
是数字0
和1
的单个元组的列表.
[(0, 1)]
is a list of a single tuple of the numbers 0
and 1
.
[(0, 1)] * n
复制列表中的元组,所以我们得到
[(0, 1)] * n
duplicates the tuple inside of the list, so we get
[(0, 1), (0, 1), ..., (0, 1), (0, 1)]
然后,如果我们看一下itertools.product
函数,我们想将每个元组作为单个参数传递.因此,我们使用*
运算符将列表解压缩为itertools.product
函数的参数.因此,我们的功能等同于:
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))
计算n
0
s和1
s的所有排列.
which computes all permutations of the n
0
s and 1
s.
请注意,itertools.product
采用一个repeat
参数,该参数应用于执行此类操作:
Note that itertools.product
takes a repeat
parameter, which should be used to do this sort of thing:
itertools.product((0, 1), repeat=n)
要进行排列,可以使用itertools.permutations
函数:
To do permutations, you can use the itertools.permutations
function:
def pick_into_three_bags(n):
return itertools.permutations(range(n), 3)
这篇关于生成大小为n的二进制数作为元组:itertools.product(* [(0,1)] * n)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!