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

2022-01-20 00:00:00 python list tuples

问题描述

在很多地方,(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?


解决方案

来自 Python 常见问题解答:

列表和元组虽然在许多方面相似,但通常以根本不同的方式使用.元组可以被认为类似于 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.

通常按照惯例,您不会仅仅根据其(不)可变性来选择列表或元组.您可以为完全不同的数据片段的小集合选择一个元组,其中成熟的类过于重量级,而为任何合理大小的集合选择一个列表,其中您拥有一组同质数据.

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.

相关文章