我刚刚找到了这条说明
itertools.product(*[(0, 1)] * n)
由 PAG 发布。
有人可以解释一下它是如何工作的吗?
- 我正在尝试找到一种在 3 个袋子中不重复 n 个元组的情况下进行排列的方法 如果我愿意的话我只能使用itertools。谢谢
最佳答案
[(0, 1)]
是数字 0
和 1
的单个元组的列表。
[(0, 1)] * n
复制列表内的元组,因此我们得到
[(0, 1), (0, 1), ..., (0, 1), (0, 1)]
然后,如果我们查看 itertools.product
函数,我们希望将每个元组作为单个参数传递。因此,我们使用 * 运算符将列表解压缩为 itertools.product 函数的参数。所以,我们的函数相当于:
itertools.product((0, 1), (0, 1), ..., (0, 1), (0, 1))
计算 n
0
和 1
的所有排列。
请注意,itertools.product
采用一个 repeat
参数,该参数应该用于执行此类操作:
itertools.product((0, 1), repeat=n)
<小时/>
要进行排列,您可以使用itertools.permutations
函数:
def pick_into_three_bags(n):
return itertools.permutations(range(n), 3)
关于python - 生成大小为 n 的二进制数作为元组 : itertools. Product(*[(0, 1)] * n),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16330105/