生成大小为n的二进制数作为元组:itertools.product(* [(0,1)] * n) [英] generating binary numbers of size n as tuples : itertools.product(*[(0, 1)] * n)

查看:159
本文介绍了生成大小为n的二进制数作为元组:itertools.product(* [(0,1)] * n)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我刚刚找到了此说明

  • I just found this instruction

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

由PAG发布.

有人可以解释它的工作原理吗?

Can someone explain how it works?

推荐答案

[(0, 1)]是数字01的单个元组的列表.

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

请注意,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆