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

Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?(Python:(1,2,3) 和 [1,2,3] 有什么区别,我应该什么时候使用它们?)
本文介绍了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?

推荐答案

来自 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.

这篇关于Python:(1,2,3) 和 [1,2,3] 有什么区别,我应该什么时候使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)