假设我有这样的函数:
def f():
x = np.arange(100)
return x[:5]
Run Code Online (Sandbox Code Playgroud)
f返回ay,这是x上的视图.
x还会在后台使用内存吗?
如果返回视图x则不会被垃圾回收.此外,它仍然可以访问base.
>>> y = f()
>>> y.base
array([ 0, 1, 2, 3, 4, 5, 6, ...., 99])
Run Code Online (Sandbox Code Playgroud)
简短回答:是的.虽然x你的切片将保持活力.请参阅基本切片的文档.
您应该在返回之前复制视图.
return x[:5].copy()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
142 次 |
| 最近记录: |