我的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.
所以==测试值测试是看他们是否相同的对象?
由于这篇文章中的其他人详细回答了==和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