根据文档,
ndarray.flat
是数组的迭代器,而ndarray.ravel
(如果可能) 返回一个扁平化的数组。那么我的问题是,在什么情况下应该使用其中之一?
在像下面代码中这样的赋值语句中,哪个更好作为rvalue?import numpy as np
x = np.arange(2).reshape((2,1,1))
y = np.arange(3).reshape((1,3,1))
z = np.arange(5).reshape((1,1,5))
mask = np.random.choice([True, False], size=(2,3,5))
# netCDF4 module wants this kind of boolean indexing:
nc4slice = tuple(mask.any(axis=axis) for axis in ((1,2),(2,0),(0,1)))
indices = np.ix_(*nc4slice)
ncrds = 3
npnts = (np.broadcast(*indices)).size
points = np.empty((npnts, ncrds))
for i,crd in enumerate(np.broadcast_arrays(x,y,z)):
# Should we use ndarray.flat ...
points[:,i] = crd[indices].flat
# ... or ndarray.ravel():
points[:,i] = crd[indices].ravel()
asarray
的那一行。我确实知道结果是相同的。实际上,我的问题是在使用flat
和使用ravel
时,numpy在上述代码中做了什么(在幕后)? - joanpauasarray
方法在输入已经是数组时不会执行任何操作,那么当输入是迭代器时,asarray
会做什么呢?文档没有提到数组迭代器。 - joanpau