查找2D数组Python的长度

Ron*_*ing 77 python arrays

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

例如,

Input = ([[1, 2], [3, 4], [5, 6]])`
Run Code Online (Sandbox Code Playgroud)

应显示为3行和2列.

Ósc*_*pez 137

像这样:

numrows = len(input)    # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example
Run Code Online (Sandbox Code Playgroud)

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

  • 只要它不是锯齿状阵列,这是理想的. (4认同)
  • @Makoto那是对的.我在答案中加入了这个假设. (3认同)

Aka*_*all 33

你可以用numpy.shape.

import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])
Run Code Online (Sandbox Code Playgroud)

结果:

>>> x
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.shape(x)
(3, 2)
Run Code Online (Sandbox Code Playgroud)

元组中的第一个值是数行= 3; 元组中的第二个值是列数= 2.

  • 谢谢,我不想在这件事上使用 numpy (2认同)

小智 14

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

sum(len(x) for x in input)
Run Code Online (Sandbox Code Playgroud)


mac*_*how 10

假设输入[row] [col],

    rows = len(input)
    cols = map(len, input)  #list of column lengths
Run Code Online (Sandbox Code Playgroud)