根据文档,ndarray.flat是数组上的迭代器,而ndarray.ravel返回一个扁平数组(如果可能的话)。所以我的问题是,我们什么时候该用一个还是另一个?
在下面的代码中,哪一个更像是赋值中的值?

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()

最佳答案

你也不需要。crd[mask]已经是1-d了。如果是,numpy总是先调用np.asarray(rhs),因此如果不需要为ravel进行复制,也是一样的。当需要拷贝时,我想ravel当前可能更快(我没有计时)。
如果您知道可能需要一个拷贝,而这里您知道什么都不需要,那么实际上重塑points可能是最快的。因为你通常不需要最快的速度,我认为这更多的是一个品味问题,而且个人可能会使用ravel

08-24 16:36