简体   繁体   English

元组与python中的列表对象

[英]tuple vs list objects in python

Can someone explain me this? 有人可以解释一下吗?

>>> [] is []
False
>>> () is ()
True
>>> (1,) is (1,)
False

I understand that I should use "==" instead of "is"to compare the values, I am just wondering why it is this way? 我明白我应该使用“==”代替“是”来比较这些值,我只是想知道为什么会这样?

is is based on object identity. is基于对象身份。 IE, are the left and right the same object? IE,左右是同一个对象吗?

In all these cases, the objects would ordinarily be different (since you have six separate literals). 在所有这些情况下,对象通常会有所不同(因为你有六个单独的文字)。 However, the empty tuples are the same object due to implementation-dependent interning. 但是,由于依赖于实现的实习,空元组是同一个对象。 As you noted, you should never rely on this behavior. 如您所述,您绝不应该依赖此行为。

Note that mutable objects can not be interned, which means the first must be false. 请注意,可变对象无法实现,这意味着第一个必须为false。

Be careful when comparing by id. 通过id比较时要小心。 If an object is GC'd the id can be reused! 如果一个对象是GC,那么id可以被重用!

>>> id([])==id([])
True

or even 甚至

>>> id([1,2,3])==id(["A","B","C"])
True

Think of it this way: In your first case, for immutable objects like tuples, it's safe for the python implementation to share them if they're identical: 可以这样想:在第一种情况下,对于像元组这样的不可变对象,如果它们是相同的,那么python实现可以安全地共享它们:

>>> a = ()
>>> b = ()
>>> a is b
True

Now consider: 现在考虑:

>>> a = []
>>> b = []
>>> a.append("foo")
>>> print a,b
['foo'] []

It's not possible for a and b to be the same object, because modifying a shouldn't modify b. a和b不可能是同一个对象,因为修改a不应该修改b。

In your final example, you're back to immutable tuples. 在最后一个例子中,您将回到不可变元组。 The Python implementation is allowed to make them the same object, but isn't required to, and in this case it doesn't (it's basically a space/time tradeoff - if you used a lot of (1,) in your program you could save memory if they were interned, but it would cost runtime to determine if any given tuple was a (1,) that could share the object). 允许 Python实现使它们成为相同的对象,但不是必需的,在这种情况下它不会(它基本上是一个空间/时间权衡 - 如果你在程序中使用了很多(1,)如果他们被实习,可以节省内存,但是确定任何给定的元组是否是可以共享对象的(1,)都需要运行时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM