如何使用np.array声明具有不同行长的二维数组? [英] How to declare a 2 dimensional array with different row lengths using np.array?

查看:105
本文介绍了如何使用np.array声明具有不同行长的二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想要一个2行矩阵,第一行的长度为1,第二行的长度为2.

For example, I want a 2 row matrix, with a first row of length 1, and second row of length 2. I could do,

list1 = np.array([1])    

list2 = np.array([2,3])    

matrix = []    

matrix.append(list1)    

matrix.append(list2)    

matrix = np.array(matrix)    

我想知道是否可以在不执行上述过程的情况下直接在程序的开头声明这种形状的矩阵吗?

I wonder if I could declare a matrix of this shape directly in the beginning of a program without going through the above procedure?

推荐答案

矩阵是通过定义数字的矩形数组. NumPy不支持不具有矩形形状的数组.当前,您的代码产生的是一个数组,其中包含一个列表(matrix),其中包含两个以上的数组.

A matrix is by definition a rectangular array of numbers. NumPy does not support arrays that do not have a rectangular shape. Currently, what your code produces is an array, containing a list (matrix), containing two more arrays.

array([array([1]), array([2, 3])], dtype=object)

我真的不知道这种形状的目的是什么,并且建议您对这种形状所做的任何事情都简单地使用嵌套列表.但是,如果您发现NumPy对该结构有一些用途,则可以像这样更惯用地生成它:

I don't really see what the purpose of this shape could be, and would advise you simply use nested lists for whatever you are doing with this shape. Should you have found some use for this structure with NumPy however, you can produce it much more idiomatically like this:

>>> np.array([list1,list2])   
array([array([1]), array([2, 3])], dtype=object)

这篇关于如何使用np.array声明具有不同行长的二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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