Python:(1,2,3)和[1,2,3]有什么区别,我什么时候应该使用它们?

问题描述:

在许多地方,(1,2,3)(一个元组)和[1,2,3](一个列表)可以互换使用.

In many places, (1,2,3) (a tuple) and [1,2,3] (a list) can be used interchangeably.

我什么时候应该使用其中一个,为什么?

When should I use one or the other, and why?

来自

列表和元组在许多方面都相似,但通常以根本不同的方式使用.元组可以被认为类似于Pascal记录或C结构.它们是相关数据的小集合,这些数据可能属于不同类型,它们作为一组进行操作.例如,笛卡尔坐标适当地表示为两个或三个数字的元组.

Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers.

另一方面,列表更像其他语言中的数组.它们倾向于容纳不同数量的对象,这些对象具有相同的类型并且可以一对一地进行操作.

Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one.

通常,按照惯例,您不会仅基于列表的(im)可变性来选择列表或元组.您将为完全不同的数据的小型集合选择一个元组,而完整的类将过于繁重,而对于具有合理数据集的任何合理大小的集合,则选择一个列表.

Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data.