在Python中,以下两个相等测试是否等效?
n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!'
这是否适用于你要比较实例(a list say)的对象?
好的,这样可以回答我的问题:
L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't.
因此,==测试重视在哪里is进行测试以查看它们是否是同一对象?
==
is
如果两个变量指向同一个对象,则返回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