In [173]: alist = [np.array([1,2,3]),
...: np.array(['a', 'b','c']),
...: np.array(['text1', 'text2', 'text3'])
...: ]
In [174]: alist
Out[174]:
[array([1, 2, 3]),
array(['a', 'b', 'c'], dtype='<U1'),
array(['text1', 'text2', 'text3'], dtype='<U5')]
In [175]: np.array(alist)
Out[175]:
array([['1', '2', '3'],
['a', 'b', 'c'],
['text1', 'text2', 'text3']], dtype='<U21')
np.array 尝试使多维数组尽可能高。 3个大小相同的数组可以组成一个(3,3)。
为避免我们必须创建所需形状和 dtype 的目标数组,并从列表中分配值:
In [178]: arr = np.empty(3, object)
In [179]: arr[:] = alist
In [180]: arr
Out[180]:
array([array([1, 2, 3]), array(['a', 'b', 'c'], dtype='<U1'),
array(['text1', 'text2', 'text3'], dtype='<U5')], dtype=object)
如果列表包含不同大小的数组(或其他对象),np.array 回退到为这些项目创建一个对象 dtype 数组。但请注意警告,并记住这是一个后备选项,并且如您所见,不是默认行为。
In [181]: alist.append([1,2])
In [182]: np.array(alist)
<ipython-input-182-7512d762195a>: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.
np.array(alist)
Out[182]:
array([array([1, 2, 3]), array(['a', 'b', 'c'], dtype='<U1'),
array(['text1', 'text2', 'text3'], dtype='<U5'), list([1, 2])],
dtype=object)
再说一遍我的评论 - 为什么你想要一个数组数组?与原始列表相比,这有什么优势?