Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中生成二进制数的二维数组_Python_List - Fatal编程技术网

在python中生成二进制数的二维数组

在python中生成二进制数的二维数组,python,list,Python,List,这就是我在Python中尝试的` input = [] for i in range(10): n = getBin(i, 4) input.append(n) print input 它的作用是: ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001'] 我需要的是: [[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 1, 1

这就是我在Python中尝试的`

input = []
for i in range(10):
  n = getBin(i, 4)
  input.append(n)
print input
它的作用是:

['0000', '0001', '0010', '0011', '0100', 
 '0101', '0110', '0111', '1000', '1001']
我需要的是:

[[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 1, 1], [0, 1, 0, 0],
 [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 1]]
与(0,1)和4次重复一起使用:

input = [list(x) for x in itertools.product((0, 1), repeat=4)]
如果您对
tuple
s的
list
而不是
list
s的
list
没有意见,您可以简单地执行以下操作:

input = list(itertools.product((0, 1), repeat=4))
或者最简单的是,如果您仍要对其进行迭代,则无需将其设置为
列表

input = itertools.product((0, 1), repeat=4)
最后,
(0,1)
可能是
范围(2)
,但这几乎不是一个改进



itertools.product
通常会尝试以您提供的格式返回。因此,通过输入一个字符串,它返回一个字符串。给它一个列表,它…几乎返回一个列表(返回一个元组)

你的
getBin
以字符串格式返回一个二进制数,我们将每个字符转换为一个整数,并返回一个列表

result = [map(int, getBin(i,4)) for i in range(10)]
比如说,

def getBin(number, total):
    return bin(number)[2:].zfill(total)

result = [map(int, getBin(i, 4)) for i in range(10)]

print result
输出

[[0, 0, 0, 0],
 [0, 0, 0, 1],
 [0, 0, 1, 0],
 [0, 0, 1, 1],
 [0, 1, 0, 0],
 [0, 1, 0, 1],
 [0, 1, 1, 0],
 [0, 1, 1, 1],
 [1, 0, 0, 0],
 [1, 0, 0, 1]]

getBin
有库函数吗?@GrijeshChauhan没有。OP并没有说明这是如何实现的。因此,我必须自己实施它。它就在我的答案中。请检查。不确定,但我认为。第一个选项是我想要的。以同样的方式,我想要浮点数,数字将在点后包含大约10位数字(例如0.0001221215)。数字从0到2500不等。@GrijeshChauhan,我假设这个新问题是前一个问题的实现细节,因为前一个输出是这个问题的输入。利用这些知识,我正在更改
getBin
中的
itertools.product
,以提供解决方案,而不需要任何额外的code@GrijeshChauhan好啊我正在为上面的问题添加一个新的问题:如何将这些二进制数保存在txt文件中。每行应该包含上述问题中的4位。