查找多维Python数组的维 [英] Find the dimensions of a multidimensional Python array

查看:118
本文介绍了查找多维Python数组的维的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,是否可以编写一个返回多维数组维的函数(假设数组维没有锯齿)?

In Python, is it possible to write a function that returns the dimensions of a multidimensional array (given the assumption that the array's dimensions are not jagged)?

例如,[[2,3], [4,2], [3,2]]的尺寸将为[3, 2],而[[[3,2], [4,5]],[[3,4],[2,3]]]的尺寸将为[2,2,2].

For example, the dimensions of [[2,3], [4,2], [3,2]] would be [3, 2], while the dimensions of [[[3,2], [4,5]],[[3,4],[2,3]]] would be [2,2,2].

Python是否有任何内置函数可以返回多维数组的所有维,还是我需要自己实现此函数?

Does Python have any built-in functions that will return all of the dimensions of a multidimensional array, or will I need to implement this function myself?

推荐答案

不,没有内置内容,因为使用这样的数组" 1 可能会产生锯齿,并且维度"或形状"根本没有任何意义.因此,您必须自己编写.如果您可以假设所有维度的一致性,则可以执行以下操作:

No, there's nothing built-in because with such "arrays"1 it can be jagged and the concept of "dimensions" or "shape" doesn't make any sense at all. So, you'll have to write your own. If you can make an assumption of uniformity along all dimensions, you can proceed as follows:

dim1 = len(a)
dim2 = len(a[0])
dim3 = len(a[0][0])
.
.
.

使此递归处理所有尺寸非常容易.这应该做到:

It'd be pretty easy to make this recursive to handle all dimensions. This should do it:

def dim(a):
    if not type(a) == list:
        return []
    return [len(a)] + dim(a[0])

但是,如果您需要类似的内容,则可能需要考虑查看具有 NumPy 数组的数组href ="http://docs.scipy.org/doc/numpy/reference/produced/numpy.ndarray.shape.html" rel ="noreferrer"> numpy.ndarray.shape 它将为您提供寻找.

But if you need something like this, you might want to consider looking at NumPy arrays which have numpy.ndarray.shape which would give you what you're looking for.

from numpy import array
l = [[2, 3], [4, 2], [3, 2]]
a = array(l)
print a.shape

输出

(3, 2)

1 用引号引起来,因为您不是真正在看数组,而是在看一个列表,一个列表列表或一个列表列表....

1 In scare quotes because you're not really looking at array, you're looking at a list, or a list of lists, or a list of list of lists....

这篇关于查找多维Python数组的维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆