重塑i时numpy数组的getrefcount发生了什么

2024-09-30 06:33:05 发布

您现在位置:Python中文网/ 问答频道 /正文

当你重塑一个np.array?你知道吗

一旦我做了系统计数. 我得到了不同的打印结果(系统getrefcount(2)和打印(系统getrefcount(1))


foo1 = np.array([1,2,3])
foo2 = foo1.reshape(3,1)

print(sys.getrefcount(foo1))
print(sys.getrefcount(foo2))

Tags: 系统npsysarray计数print重塑foo1
2条回答

我假设:

print(sys.getrefcount(foo1))
2
print(sys.getrefcount(foo2))
3

根据文件:

sys.getrefcount(object)

    Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().

通过您的命令:foo2 = foo1.reshape(3,1)您引用了对象1,因此这总共导致了3个引用

这是因为foo2保留了一个对foo的内部引用(它不是数组数据的所有者),因此它总共还有一个额外的引用。你知道吗

下一个代码

import numpy as np
import sys

foo1 = np.array([1,2,3])
foo2 = foo1.reshape(3,1)

print(sys.getrefcount(foo1), sys.getrefcount(foo2))

产生以下结果:

3 2

现在,测试这个:

foo1 = np.array([1,2,3])
foo2 = foo1.reshape(3,1).copy()

print(sys.getrefcount(foo1), sys.getrefcount(foo2))

输出是:2 2,因为现在foo2在复制了foo内容之后有了自己的数据,foo的引用计数减少了。你知道吗

相关问题 更多 >

    热门问题