我的Google-fu让我失望了.
在Python中,以下两个相等的测试是否等效?
n = 5
# Test one.
if n == 5:
print 'Yay!'
# Test two.
if n is 5:
print 'Yay!'
Run Code Online (Sandbox Code Playgroud)
对于您要比较实例的对象(list比如说),这是否适用?
好的,所以这样的答案我的问题:
L = []
L.append(1)
if L == [1]:
print 'Yay!'
# Holds true, but...
if L is [1]:
print 'Yay!'
# Doesn't.
Run Code Online (Sandbox Code Playgroud)
所以==测试值测试的地方is是否是同一个对象?
为什么以下在Python中出现意外行为?
>>> a = 256
>>> b = 256
>>> a is b
True # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False # What happened here? Why is this False?
>>> 257 is 257
True # Yet the literal numbers compare properly
Run Code Online (Sandbox Code Playgroud)
我使用的是Python 2.5.2.尝试一些不同版本的Python,似乎Python 2.3.3显示了99到100之间的上述行为.
基于以上所述,我可以假设Python在内部实现,使得"小"整数以不同于大整数的方式存储,is运算符可以区分.为什么泄漏抽象?当我不知道它们是否是数字时,比较两个任意对象以查看它们是否相同的更好的方法是什么?
可能重复:
Python"is"运算符使用整数意外运行
今天我试着调试我的项目,经过几个小时的分析,我得到了这个:
>>> (0-6) is -6
False
Run Code Online (Sandbox Code Playgroud)
但,
>>> (0-5) is -5
True
Run Code Online (Sandbox Code Playgroud)
你能解释一下,为什么?也许这是某种错误或非常奇怪的行为.
> Python 2.7.3 (default, Apr 24 2012, 00:00:54) [GCC 4.7.0 20120414 (prerelease)] on linux2
>>> type(0-6)
<type 'int'>
>>> type(-6)
<type 'int'>
>>> type((0-6) is -6)
<type 'bool'>
>>>
Run Code Online (Sandbox Code Playgroud)