【发布时间】:2021-04-18 19:55:18
【问题描述】:
我正在比较一个 numpy 数组的两个元素。 id() 函数为两个元素获取的内存地址不同。此外,is 运算符表明这两个元素不相同。
但是,如果我使用 == 运算符比较两个数组元素的内存地址,则会发现这两个元素是相同的。
当两个内存地址不同时,我无法理解== 运算符如何将输出输出为True。
下面是我的代码。
import numpy as np
a = np.arange(8)
newarray = a[np.array([3,4,2])]
print("Initial array : ", a)
print("New array : ", newarray)
# comparison of two element using 'is' operator
print("\ncomparison using is operator : ",a[3] is newarray[0])
# comparison of memory address of two element using '==' operator
print("comparison using == opertor : ", id(a[3]) == id(newarray[0]))
# memory address of both elements of array
print("\nMemory address of a : ", id(a[3]))
print("Memory address of newarray : ", id(newarray[0]))
输出:
初始数组:[0 1 2 3 4 5 6 7]
新数组:[3 4 2]
使用is 运算符比较:False
使用== 运算符进行比较:True
a的内存地址:2807046101296
newarray的内存地址:2808566470576
【问题讨论】:
标签: arrays python-3.x numpy operators deep-copy