元组/列表之间的区别是什么?它们的优点/缺点是什么?


当前回答

关键的区别是元组是不可变的。这意味着一旦创建了元组,就不能更改其中的值。

因此,如果您需要更改值,请使用List。

元组的好处:

性能略有改善。 元组是不可变的,可以用作字典中的键。 如果你不能改变它,其他人也不能,也就是说你不需要担心任何API函数等改变你的元组没有被要求。

其他回答

list和tuple的区别

Literal someTuple = (1,2) someList = [1,2] Size a = tuple(range(1000)) b = list(range(1000)) a.__sizeof__() # 8024 b.__sizeof__() # 9088 Due to the smaller size of a tuple operation, it becomes a bit faster, but not that much to mention about until you have a huge number of elements. Permitted operations b = [1,2] b[0] = 3 # [3, 2] a = (1,2) a[0] = 3 # Error That also means that you can't delete an element or sort a tuple. However, you could add a new element to both list and tuple with the only difference that since the tuple is immutable, you are not really adding an element but you are creating a new tuple, so the id of will change a = (1,2) b = [1,2] id(a) # 140230916716520 id(b) # 748527696 a += (3,) # (1, 2, 3) b += [3] # [1, 2, 3] id(a) # 140230916878160 id(b) # 748527696 Usage As a list is mutable, it can't be used as a key in a dictionary, whereas a tuple can be used. a = (1,2) b = [1,2] c = {a: 1} # OK c = {b: 1} # Error

列表用于循环,元组用于结构。“%s %s”%元组。

列表通常是同构的,元组通常是异构的。

列表是可变长度的,元组是固定长度的。

如果你去散步,你可以随时在(x,y)元组中记下你的坐标。

如果你想记录你的旅程,你可以每隔几秒钟将你的位置添加到一个列表中。

但你不能反过来做。

列表是可变的;元组不是。

从docs.python.org/2/tutorial/datastructures.html

元组是不可变的,通常包含的异构序列 通过解包访问的元素(参见本节后面的内容) 或者索引(在命名元组的情况下甚至通过属性)。列表 是可变的,它们的元素通常是同质的和 通过遍历列表来访问。

List是可变的,tuples是不可变的。可变和不可变之间的主要区别是当您试图追加一个项时内存的使用。

当你创建一个变量时,一些固定的内存被分配给变量。如果它是一个列表,则分配的内存比实际使用的要多。例如,如果当前内存分配是100个字节,当你想追加第101个字节时,可能会再分配100个字节(在这种情况下总共是200个字节)。

然而,如果你知道你不经常添加新元素,那么你应该使用元组。Tuples精确地分配所需的内存大小,从而节省内存,特别是当您使用大块内存时。