【发布时间】:2016-09-02 05:37:19
【问题描述】:
a = 2
b = 2
print(b is a)
a = [2]
b = [2]
print(b is a)
第一个print 返回True,第二个print 返回False。这是为什么呢?
【问题讨论】:
-
@mgilson 谢谢!
标签: python python-3.x
a = 2
b = 2
print(b is a)
a = [2]
b = [2]
print(b is a)
第一个print 返回True,第二个print 返回False。这是为什么呢?
【问题讨论】:
标签: python python-3.x
在 Python 中,小整数被记忆以提高效率。
所以,b is a 是 True,因为它们在内存中的位置相同。
is 检查对象身份。如果您想检查是否相等,请使用 == 除了 None 在这种情况下似乎普遍认为使用 is
>>> a = 2
>>> b = 2
>>> id(a)
1835382448
>>> id(b)
1835382448
【讨论】:
b 和a 在分配给[2] 时在内存中的位置不同?他们不是指向同一个对象吗?请原谅我的知识有限
[2] 时在内存中的位置不一样? 这是因为每次你写 [2] 时都会创建一个 新数组。您没有重用现有数组。
is 检查对象身份(列表a 与列表b 相同)。并且== 比较值标识(是存储在变量a 中的内容与存储在变量b 中的内容相同)
所以在你的情况下。 [2] 是值,虽然变量a 和变量b 都存储了这个值,但它们并不相同(你可以修改a,而b 不会改变)
如果您添加另一个变量并将其指向a,您可能会看到以下行为:
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [2]
>>> b = [2]
>>> a == b
True
>>> a is b
False
>>> c = a
>>> c == a
True
>>> c is a
True
【讨论】: