如何解决生成生成numpy数组
我正在尝试使用下面的代码生成一组数组。我将尝试解释我所做的事情
第一:
example = np.zeros(8,dtype=int)
print(example)
这给了我输出:
[0 0 0 0 0 0 0 0]
然后:
input=np.array([],int)
for i in range(0,8):
if i <8:
example[i-1]=0
example[i]=1
print(example)
input = np.append(input,example)
print(input)
然后给了我
[0 1 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0]
[0 0 0 1 0 0 0 0]
[0 0 0 0 1 0 0 0]
[0 0 0 0 0 1 0 0]
[0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 1]
最后我要这样做
input = np.append(input,example)
这给了我:[1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1]
但是这就是我想要的方式:
[[1 0 0 0 0 0 0 0]
[0 1 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0]
[0 0 0 1 0 0 0 0]
[0 0 0 0 1 0 0 0]
[0 0 0 0 0 1 0 0]
[0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 1]]
或类似的东西。现在,我尝试进行搜索,无论尝试如何,都会遇到错误。希望我能尽快得到。
解决方法
如果我正确理解了您的问题,那么您会追随身份矩阵。
X = np.identity(8,dtype=int)
,
您可以使用.reshape()
重塑数组的形状(不要使用input
作为变量名,这里myInput
应该是您的input
变量):
myInput = myInput.reshape(8,8)
您也可以使用np.identity
缩短它:
myInput = np.identity(8,dtype=int)
,
要完成尝试,您应该写input = np.append(input,example).reshape(8,8)
。
另外,您可以使用out = np.diag(np.ones(8))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。