IPython中数组元素的ID更改 [英] ID of an array element changes in IPython

查看:77
本文介绍了IPython中数组元素的ID更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么数组元素的ID不断变化?

Why does ID of array element keeps on changing?

    In [43]: x = np.array([[1,2,3],[4,5,6],[7,8,9]])
    In [44]: print id(x[0])
    30836416
    In [45]: print id(x[0])
    31121344
    In [46]: print id(x[0])
    31471808

IPython屏幕截图

用python脚本编写时不是这种情况 当用python脚本编写时,我们得到相同的ID

This is not the case when it is written in a python script When written in python script we get the same ID

下图中还有其他观察结果

And also other observation is in the below figure

aCopy是数组a的副本. 两个数组的相同元素的id打印两次. 根据输出, 除了FIRST打印外,所有数组元素的ID(无论是同一数组还是不同的(副本))都相同. 为什么两个不同数组的相同元素的id相同? 为什么多次打印时其中一个ID是不同的?

aCopy is the copy of the array a. id for the same element of both the arrays is printed twice. According to the output, id of all the array elements whether it may be of the same array or different (copy) is same except for the FIRST print. Why id of same element of two different arrays are same? Why one of the id when printed multiple times is different?

推荐答案

CPython中的id()返回值基于参数的内存地址.

The id() return value in CPython is based on the memory address of the argument.

在程序中打印时,两次打印之间没有任何反应,因此更有可能为x[0]结果重新使用相同的地址,该结果每次都是新创建的对象.而且它是打印后收集的垃圾.

When printing in a program there is nothing happening between the prints so it is more likely the same address gets reused for the x[0] result, which is a newly created object each time. And it is garbage collected after printing.

另一方面,在IPython中,每个用户输入都永久存储在历史记录中,因此在打印之间创建对象,这使得x[0]对象不太可能放置在相同的内存地址.

In IPython on the other hand each user input is permanently stored in a history, so objects are created between the prints, which makes it more unlikely the x[0] objects get placed at the same memory address.

在IPython中一次完成两次打印时,两个对象的ID相同,但每次执行此操作时都得到一个不同的ID:

When doing two prints in one go in IPython I get the same ID for both objects, but a different one for each time I do this:

In [28]: print id(x[0]); print id(x[0])
140000637403008
140000637403008

In [29]: print id(x[0]); print id(x[0])
140000637402608
140000637402608

In [30]: print id(x[0]); print id(x[0])
140000637402928
140000637402928

当然也不保证.

这篇关于IPython中数组元素的ID更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆