Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
查找2D数组Python的长度_Python_Arrays - Fatal编程技术网

查找2D数组Python的长度

查找2D数组Python的长度,python,arrays,Python,Arrays,如何查找二维数组中有多少行和列? 比如说, Input = ([[1, 2], [3, 4], [5, 6]])` 应显示为3行2列。如下所示: numrows = len(input) # 3 rows in your example numcols = len(input[0]) # 2 columns in your example 假设所有子列表具有相同的长度(即,它不是锯齿状数组)。您可以使用numpy.shape import numpy as np x = np.arr

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

比如说,

Input = ([[1, 2], [3, 4], [5, 6]])`
应显示为3行2列。

如下所示:

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

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

您可以使用
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。

假设输入[row][col]

    rows = len(input)
    cols = map(len, input)  #list of column lengths

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

sum(len(x) for x in input)

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

假设
input[row][col]

rows = len(input)
cols = len(list(zip(*input)))

只要它不是锯齿状数组,这是理想的。哟,我想找到2D数组中所有元素的总和def sum1(input):范围内的行的总和=0(len(input)-1):范围内的列的总和(len(input[0])-1):总和=sum+input[row][col col返回总和打印sum1([[1,2],[3,4],[5,6]])它显示4而不是21(1+2+3+4+5+6=21)。我的错误在哪里?有一个更简单的解决方案:sum(sum(x)表示输入中的x)@LongBodie:错误是你从不应该的长度中减去1
Range(n)
已经给出了0,1,…,n-1。听起来你应该使用numpy数组,而不是列表谢谢,我不想用numpy来做这件事太好了,这正是我需要的!在我的例子中,我可以计算一个列表中的所有元素,最多2次:sum(len(x),如果是instance(x,list),则为len(x),否则在某些_列表中为x计算1)