查找2D数组Python的长度

2024-06-07 16:29:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如

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

应显示为3行2列。


Tags: input数组行和列
3条回答

像这样:

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

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

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

sum(len(x) for x in input)

您可以使用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;元组中的第二个值是number of columns=2。

相关问题 更多 >

    热门问题