我知道用 Python,
[1,2,3][0:2]=7
不起作用,因为右侧必须是可迭代的。
但是,同样的事情适用于 NumPy ndarrays:
a=np.array([1,2,3])
a[0:2]=9
a
这和广播是一样的机制吗?在 https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html ,据说广播仅用于算术运算。
请您参考如下方法:
是的,赋值遵循与广播相同的规则,因为您还可以将一个数组赋值给另一个数组的项。然而,这要求第二个数组的形状可以广播到目标切片/数组形状。
Assigning values to indexed arrays中也提到了这一点文档:
As mentioned, one can select a subset of an array to assign to using a single index, slices, and index and mask arrays. The value being assigned to the indexed array must be shape consistent (the same shape or broadcastable to the shape the index produces).
