python中numpy数组的len()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43081809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:30:03  来源:igfitidea点击:

len() of a numpy array in python

pythonnumpymultidimensional-arrayvariable-length

提问by Monica Heddneck

If I use len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]])), I get back 3.

如果我使用len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]])),我会返回 3。

Why is there no argument for len()about which axis I want the length of in multidimensional arrays? This is alarming. Is there an alternative?

为什么没有len()关于我想要多维数组中哪个轴的长度的争论?这令人担忧。有替代方案吗?

回答by hpaulj

What is the lenof the equivalent nested list?

什么是len等效嵌套列表?

len([[2,3,1,0], [2,3,1,0], [3,2,1,1]])

With the more general concept of shape, numpydevelopers choose to implement __len__as the first dimension. Python maps len(obj)onto obj.__len__.

有了更一般的概念shapenumpy开发人员选择实现__len__作为第一个维度。Python 映射len(obj)obj.__len__.

X.shapereturns a tuple, which does have a len- which is the number of dimensions, X.ndim. X.shape[i]selects the ithdimension (a straight forward application of tuple indexing).

X.shape返回一个元组,它有一个len- 这是维数,X.ndimX.shape[i]选择ith维度(元组索引的直接应用)。

回答by Dmitry Pleshkov

Easy. Use .shape.

简单。使用.shape.

>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.

回答by Batman

You can transpose the array if you want to get the length of the other dimension.

如果您想获得另一个维度的长度,您可以转置数组。

len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)