列表和元组有什么区别? [英] What's the difference between lists and tuples?

查看:24
本文介绍了列表和元组有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别?

元组/列表的优点/缺点是什么?

What are the advantages / disadvantages of tuples / lists?

推荐答案

除了元组是不可变的之外,还有一个语义区别应该指导它们的使用.元组是异构数据结构(即它们的条目具有不同的含义),而列表是同构序列.元组有结构,列表有顺序.

Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.

使用这种区别可以使代码更加明确和易于理解.

Using this distinction makes code more explicit and understandable.

一个例子是成对的页码和行号来引用书中的位置,例如:

One example would be pairs of page and line number to reference locations in a book, e.g.:

my_location = (42, 11)  # page number, line number

然后,您可以将其用作字典中的键来存储位置注释.另一方面,列表可用于存储多个位置.自然地,人们可能想要在列表中添加或删除位置,因此列表是可变的是有道理的.另一方面,从现有位置添加或删除项目没有意义 - 因此元组是不可变的.

You can then use this as a key in a dictionary to store notes on locations. A list on the other hand could be used to store multiple locations. Naturally one might want to add or remove locations from the list, so it makes sense that lists are mutable. On the other hand it doesn't make sense to add or remove items from an existing location - hence tuples are immutable.

在某些情况下,您可能希望更改现有位置元组中的项目,例如在遍历页面各行时.但是元组不变性迫使您为每个新值创建一个新的位置元组.从表面上看,这似乎很不方便,但使用像这样的不可变数据是值类型和函数式编程技术的基石,可以带来巨大的优势.

There might be situations where you want to change items within an existing location tuple, for example when iterating through the lines of a page. But tuple immutability forces you to create a new location tuple for each new value. This seems inconvenient on the face of it, but using immutable data like this is a cornerstone of value types and functional programming techniques, which can have substantial advantages.

有一些关于这个问题的有趣文章,例如"Python 元组不仅仅是常量列表"了解 Python 中的元组与列表".Python 官方文档也提到了这一点

There are some interesting articles on this issue, e.g. "Python Tuples are Not Just Constant Lists" or "Understanding tuples vs. lists in Python". The official Python documentation also mentions this

元组是不可变的,通常包含一个异构序列......".

"Tuples are immutable, and usually contain an heterogeneous sequence ...".

在像 Haskell 这样的静态类型语言中,元组中的值通常具有不同的类型,并且元组的长度必须是固定的.在一个列表中,所有的值都具有相同的类型并且长度不固定.所以区别非常明显.

In a statically typed language like Haskell the values in a tuple generally have different types and the length of the tuple must be fixed. In a list the values all have the same type and the length is not fixed. So the difference is very obvious.

最后是 Python 中的 namedtuple,这使得感觉是因为元组已经应该具有结构.这强调了元组是类和实例的轻量级替代品的想法.

Finally there is the namedtuple in Python, which makes sense because a tuple is already supposed to have structure. This underlines the idea that tuples are a light-weight alternative to classes and instances.

这篇关于列表和元组有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆