numpy中list转array的问题,以及array中的object对象

这篇博客探讨了在numpy中将list转换为array时,遇到的不同情况。当list的元素维度一致,转换后的array为常规数组;而维度不一时,会变为包含多个object的array。对于这种object array,其访问方式需要注意,因为它只有一个维度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于一个list,可以通过numpy.array()方法转为array,根据list的不同情况,得到的array也有所不同:

当list的维度一样的时候,可以解释为通常的array,即:

>>> import numpy as np
>>>
>>> a = [[1,2,3],[4,5,6]]
>>> a_array = np.array(a)
>>> print(a_array)
[[1 2 3]
 [4 5 6]]
>>>

但是,当list的维度不一样的时候,则会被解释为多个object,即:

>>> import numpy as np
>>>
>>> a = [[1,2,3],[4,5,6,7]]
>>> a_array = np.array(a)
<stdin>:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
>>> print(a_array.shape)
(2,)
>>>

要想访问此时的a_array的对象,注意到,它其实只有一个维度(2,)因此:

>>> a_array[0,:] # erro
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
>>> a_array[0,] # correct
[1, 2, 3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值