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


当前回答

首先,它们都是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还可能导致别名错误(两条不同的路径 指向同一对象)。

其他回答

list的值可以随时更改,但元组的值不能更改。

优点和缺点取决于使用。如果你有这样一个你不想改变的数据,那么你应该使用tuple,否则list是最好的选择。

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

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

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

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

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

list和tuple的区别

元组和列表在Python中看起来都是相似的序列类型。

Literal syntax We use parenthesis () to construct tuples and square brackets [ ] to get a new list. Also, we can use call of the appropriate type to get required structure — tuple or list. someTuple = (4,6) someList = [2,6] Mutability Tuples are immutable, while lists are mutable. This point is the base the for the following ones. Memory usage Due to mutability, you need more memory for lists and less memory for tuples. Extending You can add a new element to both tuples and lists with the only difference that the id of the tuple will be changed (i.e., we’ll have a new object). Hashing Tuples are hashable and lists are not. It means that you can use a tuple as a key in a dictionary. The list can't be used as a key in a dictionary, whereas a tuple can be used tup = (1,2) list_ = [1,2] c = {tup : 1} # ok c = {list_ : 1} # error Semantics This point is more about best practice. You should use tuples as heterogeneous data structures, while lists are homogenous sequences.

列表是同构序列,而元组是异构数据结构。