我很惊讶
[] is not []
Run Code Online (Sandbox Code Playgroud)
评估为True.
这段代码发生了什么?真的not和is陈述在做什么?
Mar*_*ers 57
a is not b是一个特殊的运算符,相当于not a is b.
a is b如果a和b绑定到同一个对象,则运算符返回True,否则返回False.当您创建两个空列表时,您将获得两个不同的对象,因此is返回False(因此is not返回True).
Jia*_*aro 22
描述为什么会发生这种情况的最佳方式是:
这是你的例子
>>> x = []
>>> y = []
>>> print(x is y)
... False
Run Code Online (Sandbox Code Playgroud)
x并且y实际上是两个不同的列表,所以如果你添加一些东西x,它就不会出现y
>>> x.append(1)
>>> print(x)
... [1]
>>> print(y)
... []
Run Code Online (Sandbox Code Playgroud)
那么我们如何使(x is y)评估为真呢?
>>> x = []
>>> y = x
>>> print(x is y)
... True
>>> x.append(10)
>>> print(x)
... [10]
>>> print(y)
... [10]
>>> print(x is y)
... True
Run Code Online (Sandbox Code Playgroud)
如果你想看看两个列表是否有相同的内容......
>>> x = []
>>> y = []
>>> print(x == y)
... True
>>> x.append(21)
>>> print(x)
... [21]
>>> print(y)
... []
>>> print(x == y)
... False
>>> y = [21]
>>> print(x == y)
... True
Run Code Online (Sandbox Code Playgroud)