45

如何在 Python 中找到矩阵的维度。Len(A) 只返回一个变量。

编辑:

close = dataobj.get_data(timestamps, symbols, closefield)

是(我假设)生成一个整数矩阵(不太可能是字符串)。我需要找到该矩阵的大小,这样我就可以运行一些测试而不必遍历所有元素。就数据类型而言,我假设它是一个数组数组(或列表列表)。

4

10 回答 10

61

列表列表的行数将是:len(A)和列数,len(A[0])假设所有行具有相同的列数,即每个索引中的所有列表都具有相同的大小。

于 2012-11-24T09:32:48.673 回答
34

如果你使用 NumPy 数组,可以使用 shape。例如

  >>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
  >>> a
  array([[[ 1,  2,  3],
         [ 1,  2,  3]],

         [[12,  3,  4],
         [ 2,  1,  3]]])
 >>> a.shape
 (2, 2, 3)
于 2012-11-24T11:02:15.347 回答
11

正如 Ayman farhat 所提到的,您可以使用简单的方法 len(matrix) 来获取行的长度并获取第一行的长度来获取编号。使用 len(matrix[0]) 的列数:

>>> a=[[1,5,6,8],[1,2,5,9],[7,5,6,2]]
>>> len(a)
3
>>> len(a[0])
4

您还可以使用一个库来帮助您处理矩阵“numpy”:

>>> import numpy 
>>> numpy.shape(a)
(3,4)
于 2017-05-14T04:42:14.693 回答
8

要在 NumPy 中获得正确数量的维度:

len(a.shape)

在第一种情况下:

import numpy as np
a = np.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
print("shape = ",np.shape(a))
print("dimensions = ",len(a.shape))

输出将是:

shape =  (2, 2, 3)
dimensions =  3
于 2019-05-05T14:51:57.720 回答
4

正确答案如下:

import numpy 
numpy.shape(a)
于 2017-09-04T01:43:15.727 回答
4
m = [[1, 1, 1, 0],[0, 5, 0, 1],[2, 1, 3, 10]]

print(len(m),len(m[0]))

输出

(3 4)

于 2020-06-03T01:18:57.117 回答
2

假设你有一个数组。要获取数组的尺寸,您应该使用 shape.

import numpy as np a = np.array([[3,20,99],[-13,4.5,26],[0,-1,20],[5,78,-19]])
a.shape

其输出将是 (4,3)

于 2018-10-04T06:19:31.033 回答
1

您可以使用以下方法获取 Numpy 数组的高度和重量:

int height = arr.shape[0]
int weight = arr.shape[1]

如果您的数组有多个维度,您可以增加索引来访问它们。

于 2020-05-21T21:45:56.987 回答
0

您只需使用 Numpy 即可找到矩阵维度:

import numpy as np

x = np.arange(24).reshape((6, 4))
x.ndim

输出将是:

2

这意味着这个矩阵是一个二维矩阵。

x.shape

将显示每个维度的大小。x 的形状等于:

(6, 4)
于 2020-08-07T12:38:01.710 回答
0

我看待它的一种简单方式:示例:

h=np.array([[[[1,2,3],[3,4,5]],[[5,6,7],[7,8,9]],[[9,10,11],[12,13,14]]]])

h.ndim 
4

h
array([[[[ 1,  2,  3],
         [ 3,  4,  5]],

        [[ 5,  6,  7],
         [ 7,  8,  9]],

        [[ 9, 10, 11],
         [12, 13, 14]]]])

如果您仔细观察,开头的方括号的数量决定了数组的维度。在上面要访问 7 的数组中,使用了下面的索引,h[0,1,1,0]

但是,如果我们将数组更改为 3 维,如下所示,

h=np.array([[[1,2,3],[3,4,5]],[[5,6,7],[7,8,9]],[[9,10,11],[12,13,14]]])

h.ndim
3

h

array([[[ 1,  2,  3],
        [ 3,  4,  5]],

       [[ 5,  6,  7],
        [ 7,  8,  9]],

       [[ 9, 10, 11],
        [12, 13, 14]]])

要访问上述数组中的元素 7,索引为 h[1,1,0]

于 2021-06-12T15:20:39.977 回答