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


当前回答

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

其他回答

PEP 484——类型提示说元组元素的类型可以单独类型化;这样你就可以说Tuple[str, int, float];但是一个带有list类型类的列表只能接受一个类型参数:list [str],这暗示了两者的区别实际上是前者是异构的,而后者本质上是同构的。

此外,标准库通常使用tuple作为这些标准函数的返回值,而C将返回结构体。

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

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

但你不能反过来做。

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

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

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

最重要的区别是时间!当你不想改变列表里面的数据时最好使用元组!下面是为什么使用tuple的例子!

import timeit
print(timeit.timeit(stmt='[1,2,3,4,5,6,7,8,9,10]', number=1000000)) #created list
print(timeit.timeit(stmt='(1,2,3,4,5,6,7,8,9,10)', number=1000000)) # created tuple 

在本例中,我们执行了这两条语句100万次

输出:

0.136621
0.013722200000000018

任何人都能清楚地注意到时差。

首先,它们都是Python中的非标量对象(也称为复合对象)。

元组,有序的元素序列(可以包含任何没有混叠问题的对象) 不可变(tuple, int, float, str) 使用+进行连接(当然会创建一个全新的元组) 索引 切片 Singleton(3,) # ->(3)而不是(3)# -> 3 List(其他语言中的数组),值的有序序列 可变的 单例[3] 克隆new_array = origin_array[:] 列表推导式[x**2 for x in range(1,7)]给出 [1,4,9,16,25,36](不可读)

使用list还可能导致别名错误(两条不同的路径 指向同一对象)。