开始 - 大小不同的列表列表(它们也可以是数组):
In [625]: alist = [[1,2,3],[4,5],[6]]
创建一个数组——本质上是一样的,只是引用列表。 object 需要 dtype,否则我们会收到警告。
In [626]: arr = np.array(alist, object)
In [627]: alist
Out[627]: [[1, 2, 3], [4, 5], [6]]
In [628]: arr
Out[628]: array([list([1, 2, 3]), list([4, 5]), list([6])], dtype=object)
无法连接它们:
In [629]: np.stack(arr)
Traceback (most recent call last):
File "<ipython-input-629-5e39aed5411e>", line 1, in <module>
np.stack(arr)
File "<__array_function__ internals>", line 5, in stack
File "/usr/local/lib/python3.8/dist-packages/numpy/core/shape_base.py", line 426, in stack
raise ValueError('all input arrays must have the same shape')
ValueError: all input arrays must have the same shape
将列表修改为相同大小(实际上我正在制作新列表):
In [630]: arr[1]=[4,5,0]; arr[2]=[6,0,0]
In [631]: arr
Out[631]: array([list([1, 2, 3]), list([4, 5, 0]), list([6, 0, 0])], dtype=object)
在此调用数组不会改变任何东西:
In [632]: np.array(arr)
Out[632]: array([list([1, 2, 3]), list([4, 5, 0]), list([6, 0, 0])], dtype=object)
astype 也无济于事。 astype 无法更改形状或将数组/序列放入单个元素槽中。
In [633]: arr.astype(int)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<ipython-input-633-486203c45b85>", line 1, in <module>
arr.astype(int)
ValueError: setting an array element with a sequence.
但我可以将stack 应用于此:
In [634]: np.stack(arr)
Out[634]:
array([[1, 2, 3],
[4, 5, 0],
[6, 0, 0]])
另一种选择是将数组转换回列表,然后从中生成数组:
In [635]: np.array(arr.tolist())
Out[635]:
array([[1, 2, 3],
[4, 5, 0],
[6, 0, 0]])
如果我就地修改列表,我会看到 arr 和 alist 的变化,因为它们包含相同的引用:
Out[637]: array([list([1, 2, 3]), list([4, 5]), list([6])], dtype=object)
In [638]: arr[1].append(0);arr[2].extend([0,0])
In [639]: arr
Out[639]: array([list([1, 2, 3]), list([4, 5, 0]), list([6, 0, 0])], dtype=object)
In [640]: alist
Out[640]: [[1, 2, 3], [4, 5, 0], [6, 0, 0]]
如果列表/数组包含数组,则不可能进行这种就地更改。 np.append/concatenate 新建一个数组,大量复制。