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

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

问题描述

有什么区别?

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

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文档也提到了这一点

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天全站免登陆