简体   繁体   English

在python中声明矩阵数组

[英]Declare array of matrix in python

I'm new in the magic python world. 我是魔术python世界的新手。

1)I need to have an array (arrMtx) where each element of this vector is a matrix. 1)我需要一个数组(arrMtx),其中此向量的每个元素都是一个矩阵。 How I can declare the array arrMtx? 我如何声明数组arrMtx?

2)I suppose for filling the arrMtx I should do something like that: 2)我想填充arrMtx,我应该这样做:

mtx = [[0.0 for x in range(NUM_COLUMN)] for x in range(NUM_ROW)] 
arrMtx[i] = mtx

Do you have any suggestions? 你有什么建议吗?

If you want a list of 2d arrays (matrices): 如果需要二维数组(矩阵)的列表:

num_matrices = 3 ## Let's say
ncol = 3
nrow = 3
arrMtx = [[[0 for j in range(ncol)] for i in range(nrow)] for k in range(num_matrices)]

Output: 输出:

>>>[[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]

Try this simply, where n is no. 简单地尝试一下,其中n为否。 of elemnts in arrMtx arrMtx中的arrMtx

>>>[[[0.0 for x in range(NUM_COLUMN)] for x in range(NUM_ROW)]]*n #no. of elements

That means 那意味着

>>>mtx = [[0.0 for x in range(NUM_COLUMN)] for x in range(NUM_ROW)]
>>>arrMtx = [mtx] * n
NUM_COLUMN = 4
NUM_ROW = 2
NUM_MATRIX = 3
mtx = [[0.0 for x in range(NUM_COLUMN)] for x in range(NUM_ROW)] 
arrMtx = [mtx for x in range(NUM_MATRIX)]
print arrMtx

Output: 输出:

[[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]

In Python, Lists are use like vector in c++ . 在Python中, 列表的用法类似于vector in c++

In a list, you can append as you like: 在列表中,您可以随意添加

L = [0,1,2,3....]

After append list will be: 追加列表之后将是:

L.append('str')
L = [0,1,2,3,'str'....]

So, you can anything append you can want. 因此,您可以随意添加任何内容。

So make a matrix , you need list of list like: 因此,创建一个矩阵 ,您需要像这样list of list

L = [[....], [.....]....]

mtx = [[0.0 for x in range(NUM_COLUMN)] for x in range(NUM_ROW)]

Here mtx is also a matrix . 此处mtx也是一个矩阵 you can append it into another list: 您可以附加到另一个列表中:

arrMtx = [] 
arrMtx.append(mtx)

Question 1 answer: 问题1的答案:

You can declare the array arrMtx like: 您可以像这样声明array arrMtx

arrMtx = []

It's create a list. 它创建一个列表。 Then you append a list, it will be an array. 然后添加一个列表,它将是一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM