我的Google-fu让我失望了
在Python中,以下两个相等测试是否等效?
n = 5
# Test one.
if n == 5:
print 'Yay!'
# Test two.
if n is 5:
print 'Yay!'
这是否适用于对象,你将比较实例(一个列表说)?
这就回答了我的问题
L = []
L.append(1)
if L == [1]:
print 'Yay!'
# Holds true, but...
if L is [1]:
print 'Yay!'
# Doesn't.
所以==测试值测试是看他们是否相同的对象?
如果两个变量指向同一个对象(在内存中),则返回True,如果变量引用的对象相等则返回==。
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
# Make a new copy of list `a` via the slice operator,
# and assign it to variable `b`
>>> b = a[:]
>>> b is a
False
>>> b == a
True
在您的情况下,第二个测试只能工作,因为Python缓存小整数对象,这是一个实现细节。对于较大的整数,这行不通:
>>> 1000 is 10**3
False
>>> 1000 == 10**3
True
这同样适用于字符串字面量:
>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True
请看这个问题。
如果两个变量指向同一个对象(在内存中),则返回True,如果变量引用的对象相等则返回==。
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
# Make a new copy of list `a` via the slice operator,
# and assign it to variable `b`
>>> b = a[:]
>>> b is a
False
>>> b == a
True
在您的情况下,第二个测试只能工作,因为Python缓存小整数对象,这是一个实现细节。对于较大的整数,这行不通:
>>> 1000 is 10**3
False
>>> 1000 == 10**3
True
这同样适用于字符串字面量:
>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True
请看这个问题。
它们完全不同。Is检查对象的同一性,而==检查相等性(这一概念取决于两个操作数的类型)。
这只是一个幸运的巧合,“is”似乎正确地适用于小整数(例如5 == 4+1)。这是因为CPython通过使整数为单例来优化范围(-5到256)内的整数的存储。这种行为完全依赖于实现,并且不能保证在所有形式的小型转换操作下都能保留。
例如,Python 3.5也创建了短字符串单例,但将它们切片会破坏这种行为:
>>> "foo" + "bar" == "foobar"
True
>>> "foo" + "bar" is "foobar"
True
>>> "foo"[:] + "bar" == "foobar"
True
>>> "foo"[:] + "bar" is "foobar"
False
由于这篇文章中的其他人详细回答了==和is之间的区别,用于比较对象或变量,我将主要强调is和==之间的比较,用于字符串,可以给出不同的结果,我将敦促程序员谨慎使用它们。
对于字符串比较,确保使用==而不是is:
str = 'hello'
if (str is 'hello'):
print ('str is hello')
if (str == 'hello'):
print ('str == hello')
Out:
str is hello
str == hello
但是在下面的例子中== and is会得到不同的结果:
str2 = 'hello sam'
if (str2 is 'hello sam'):
print ('str2 is hello sam')
if (str2 == 'hello sam'):
print ('str2 == hello sam')
Out:
str2 == hello sam
结论与分析:
使用的是仔细比较之间的字符串。
因为是用来比较对象的,而且在Python 3+中,每个变量(如字符串)都被解释为对象,让我们看看上面的段落中发生了什么。
在python中,有一个id函数,它显示一个对象在其生命周期内的唯一常数。这个id在Python解释器的后端使用is关键字来比较两个对象。
str = 'hello'
id('hello')
> 140039832615152
id(str)
> 140039832615152
But
str2 = 'hello sam'
id('hello sam')
> 140039832615536
id(str2)
> 140039832615792