91

如何找到二维数组中有多少行和列?

例如,

Input = ([[1, 2], [3, 4], [5, 6]])`

应显示为 3 行 2 列。

4

6 回答 6

173

像这样:

numrows = len(input)    # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example

假设所有子列表都具有相同的长度(也就是说,它不是锯齿状数组)。

于 2012-05-23T03:21:34.520 回答
41

您可以使用numpy.shape.

import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])

结果:

>>> x
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.shape(x)
(3, 2)

元组中的第一个值是 number rows = 3; 元组中的第二个值是列数 = 2。

于 2012-05-23T03:24:28.933 回答
22

此外,计算总项目数的正确方法是:

sum(len(x) for x in input)
于 2016-10-25T13:03:42.920 回答
11

假设输入[行][列],

    rows = len(input)
    cols = map(len, input)  #list of column lengths
于 2012-05-23T03:26:07.063 回答
1

您也可以使用 np.size(a,1), 1 这里是轴,这将为您提供列数

于 2018-08-17T04:23:32.747 回答
0

假设input[row][col]

rows = len(input)
cols = len(list(zip(*input)))
于 2019-03-21T23:03:39.393 回答