91

How do I find how many rows and columns are in a 2d array?

For example,

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

should be displayed as 3 rows and 2 columns.

4

6 に答える 6

173

Like this:

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

Assuming that all the sublists have the same length (that is, it's not a jagged array).

于 2012-05-23T03:21:34.520 に答える
41

You can use numpy.shape.

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

Result:

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

First value in the tuple is number rows = 3; second value in the tuple is number of columns = 2.

于 2012-05-23T03:24:28.933 に答える
22

In addition, correct way to count total item number would be:

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

Assuming input[row][col],

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

You can also use np.size(a,1), 1 here is the axis and this will give you the number of columns

于 2018-08-17T04:23:32.747 に答える
0

assuming input[row][col]

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