import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.array([1, 2, 3, 4, 5])
c = a
# use 'is' to compare
print("a compares with b: ", a is b)
print("a compares with c: ", a is c)
# use '==' to compare
print("a compares with b: ", a == b)
print("a compares with c: ", a == c)
如果用python的语句“is”来比较的话,直接返回Ture或者False
如果使用‘==’来比较的话,会返回个bool值得array
use 'is' to compare:
a compares with b: False
a compares with c: True
use '==' to compare:
a compares with b: [ True True True True True]
a compares with c: [ True True True True True]
使用相同语句创建两个ndarray,当使用‘is’做比较的时候返回时False
之前不理解‘is’的具体含义,在这里查了下
is 是判断两个标识符是不是引用自一个对象,而非判断两个变量指向的存储区域存储的数据是否相同
x is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False
is not同理
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
print(a is b)
print(a == b)
False
True
总结:
is不能完全替代‘==’
再扩展一下,如何判断numpy中两个ndarray相同:
使用如下方法:
d = np.array([1, 2, 3, 4, 0])
# 判断两个ndarray中所有元素都相同
print(a == b)
print((a == b).all())
# 判断两个ndarray中同一位置上是否有相同元素
print(a == d)
print((a == d).any())
[ True True True True True]
True
[ True True True True False]
True