I tried this:
import numpy as np
a = np.empty((1, 10, 1), np.int8)
a[0] = range(10)
It throw error: ValueError: could not broadcast input array from shape (10) into shape (10,1)
您可以执行a[0, :, 0] = range(10)
。
Several options that work in this case:
a[0, :, 0] = np.arange(10) # assign to 1D slice
a[0].flat = range(10) # assign to flattened 2D slice
a[0] = np.arange(10).reshape(10, 1) # bring the rigth side into correct shape
a[0] = np.arange(10)[:, np.newaxis] # bring the rigth side into correct shape
Note the use of np.arange
instead of range
. The former directly creates an ndarray with a sequence of values, while the latter creates an iterable that needs to be converted into an array for the assignment.
In the case of assigning to flat
it makes sense to use range
because both are iterators.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.