在Python中按引用与值比较列表

sel*_*bie 2 python python-3.x

我目前正在学习3.2版本的Python.

给定两个列表变量,如何区分变量是否引用相同的列表与两个具有相同值的单独列表.

例如:

>>> foo = [1,2,3,4]
>>> bar = foo
>>> foo.append(5)
>>> foo
[1, 2, 3, 4, 5]
>>> bar
[1, 2, 3, 4, 5]
>>> foo == bar
True
Run Code Online (Sandbox Code Playgroud)

在上文中,"foo"和"bar"明显引用相同的列表.(通过在foo中附加"5"并看到该变化也反映在条形图中)证明了这一点.

现在,让我们定义第三个列表,名为"other",具有相同的值:

>>> other = [1,2,3,4,5]
>>> other == foo
True
Run Code Online (Sandbox Code Playgroud)

鉴于比较运算符在这里也返回True,它们看起来肯定是相同的列表.但是如果我们修改"其他",我们可以看到它是一个不同的列表,其中任何一个变量的变化都不会影响另一个变量.

>>> other.append(6)
>>> other == foo
False
>>> other
[1, 2, 3, 4, 5, 6]
>>> foo
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

我认为知道两个变量何时是彼此的别名而不是结构相同是有用的.但我怀疑我可能会误解其他语言的基本内容.

Mar*_*ers 7

您可以使用is运算符来确定对象标识:

>>> foo is bar
True
>>> foo is other
False
Run Code Online (Sandbox Code Playgroud)

引用文档:

对象标识的运算符isis not测试:x is y当且仅当xy是同一个对象时才是真的.x is not y产生反向真值.

检测两个变量是否引用同一对象(例如列表)的另一种方法是检查id()函数的 te返回值:

>>> id(foo)
4432316608
>>> id(bar)
4432316608
>>> id(other)
4432420232
Run Code Online (Sandbox Code Playgroud)

  • @AgentM:“in”同时使用“is”和“==”(首先测试身份,因为这对性能更好)。 (2认同)