创建空矩阵Python [英] Create empty matrix Python

查看:121
本文介绍了创建空矩阵Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想用Python创建一个空的10 * 3 * 2数组.

I simply want to create an empty 10*3*2 array with Python.

我首先想到了这些,但这是行不通的:

I first thought of these one, but this is not working:

parameters = [ [ [] * 2 ]*3 ] * 10

这给了我一个包含十个向量的向量,其中有三个[]元素:

this gives me a vector of ten vectors, with three [] elements in it:

[[[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []], 
[[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []]]

就是说,如果我想访问参数[0] [0] [1],我就超出了范围,而我想要沿着第二维的最里面向量的维数是2.

that is , if I want to access parameters[0][0][1] I am out of bounds, whereas I want a dimension 2 for the innermost vectors along the third dimension.

那我想到了

[ [ [[] * 2] ]*3 ] * 10

我当时以为[[] * 2]现在会带给我我想要的东西,这是最里面的两个元素向量.我得到

I was thinking that [[] * 2] would now bring me the thing I want, an innermost two elements vector. I obtain

[[[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], 
[[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], 
[[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]], [[[]], [[]], [[]]]]

那么,该怎么做,或者如何避免这种初始化?

So, how to do it, or how to escape this initialization?

Kd rgds.

推荐答案

我建议您将Numpy用于此类内容.它使访问列或行变得更加容易.对于您的用例,您可以

I would recommend you use Numpy for this kind of stuff. It makes accessing columns or rows much easier. For your use case you'd do

import numpy as np

matrix = np.zeros((2,3,10))
second_col = matrix[:,1,:]

Numpy还将更好地照顾您的数据,并且它在Fortran或C中实现了很多矩阵代数,因此在(可能的)将来,当您进行矩阵乘法等时,它将变得更快.

Numpy will also take better care of your data, and it implements a lot of the matrix algebra in Fortran or C so it's going to be a lot faster in the (possible) future when you're doing matrix multiplication and the likes.

这篇关于创建空矩阵Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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