简体   繁体   English

Python中的列表和元组有什么区别?

[英]What is the difference between lists and tuples in Python?

Which is more efficient? 哪个更有效率? What is the typical use of each? 每种的典型用途是什么?

Lists are mutable sequences, with lots and lots of methods (both mutating and non-mutating ones), that are most often used as general purpose containers (their items can be objects of any types at all, although it's sometimes considered better style for lists to have items that are of the same type or types to be used equivalently). 列表是可变序列,有许多方法(包括变异和非变异的方法),它们通常用作通用容器(它们的项目可以是任何类型的对象,尽管它有时被认为是更好的列表样式具有相同类型或类型的项目等效使用)。

Tuples are immutable sequences, with very few methods (all non-mutating special ones), that are most often used when you need immutability for the purpose of using a container as an item in a set or a key in a dict (though the items will also have to be immutables -- eg strings, numbers, or other nested tuples, for this to work). 元组是不可变的序列,只有很少的方法(所有非变异的特殊元素),当你需要不可变性以便将容器用作集合中的项目或字典中的键时(通过项目),最常使用这些方法也必须是不可变的 - 例如字符串,数字或其他嵌套元组,为此起作用)。 Their items can be objects of any types at all and it's perfectly normal for tuples to have items of many different and distinct types. 他们的项目可以是任何类型的对象,元组拥有许多不同类型的项目是完全正常的。

There are a few cases in which either a tuple or a list would serve just as well, and in such few cases the fact that tuples are a bit smaller and faster to build can be used to sway the decision in favor of tuples. 在一些情况下,元组或列表也可以同样起作用,并且在少数情况下,元组更小且构建更快的事实可用于影响有利于元组的决策。 For example, when a function needs to return multiple results, it's most normal to use 例如,当函数需要返回多个结果时,使用它是最正常的

return fee, fie, foo, fum

ie, return a tuple with the four items in question, rather than 即,返回一个有问题的四个项目的元组,而不是

return [fee, fie, foo, fum]

ie, return a list with the four items -- besides (small gains in) performance, the "return a tuple" common idiom also deals with the issue that often the multiple results being returned are not of the same nor interchangeable types, so, stylistically speaking, using a list might be considered a more dubious choice anyway. 也就是说,返回一个包含四个项目的列表 - 除了(小的收益)性能,“返回一个元组”常见的习惯用法也处理通常返回的多个结果不是相同的也不可互换的类型的问题,因此,从风格上来说,无论如何,使用列表可能会被认为是一个更可疑的选择。

A useful variant of tuple is its sub-type collections.namedtuple (requires Python 2.6 or better) which lets you access items by name (with attribute syntax) as well as by index (the normal way). tuple一个有用变体是它的子类型collections.namedtuple (需要Python 2.6或更高版本),它允许您按名称(使用属性语法)和索引(正常方式)访问项目。 For example, with an import collections at the top of the module, the above return statement might become... 例如,如果import collections位于模块顶部,则上述return语句可能会变为......

freturn = collections.namedtuple('freturn', 'fee fie foo fum')

def f():
  ...
return freturn(fee, fie, foo, fum)

Now, the caller of f() could use its return value as a tuple, just as before, but would gain nice alternatives such as...: 现在, f()的调用者可以像以前一样使用其返回值作为元组,但是会获得很好的替代方案,例如...:

r = f()
print r.fie

in lieu of the less immediately clear and readable 代替不那么立即清晰可读

print r[1]

It's important to note that a named tuple subclass made with collections.namedtuple has essentially no extra overhead compared with using a tuple directly, or, as the docs put it, 值得注意的是,与直接使用元组相比,使用collections.namedtuple创建的命名元组子类基本上没有额外的开销,或者正如文档所说的那样,

they are lightweight and require no more memory than regular tuples. 它们很轻巧,不需要比常规元组更多的内存。

A list is mutable , you can add elements to it. 列表是可变的 ,您可以向其中添加元素。 A tuple isn't, which means it's (slightly) more efficient. 元组不是,这意味着它(稍微)更高效。 Tuples are also hashable , so can be used as eg the key in a dictionary. 元组也是可以清除的 ,因此可以用作例如字典中的键。

Read this . 这个

Lists are mutable (can be changed), tuples are immutable. 列表是可变的(可以更改),元组是不可变的。 Typical use: it sounds rather trite but you use lists when you need to change the values. 典型用途:它听起来相当陈腐,但是当您需要更改值时使用列表。 Tuples are generally a little more efficient because of their immutability (unless you are using them like lists and duplicating them a lot...) 由于它们的不变性,元组通常效率更高一些(除非你像列表一样使用它们并且复制它们很多......)

After some reading of Python doc. 在阅读了一些Python doc之后。 on Built-in types , I created the below table to show the main differences among the six iterable containers. 在内置类型上 ,我创建了下表来显示六个可迭代容器之间的主要差异。

<pre>
Container   Notation     Index [n:m]   Mutable   Hashable
=========   ==========   ===========   =======   ========
String      ' ' or " "    position     Immutable    Yes
Range       range(,,)     position     Immutable    Yes
Tuple       (,)           position     Immutable    Yes
List        [,]           position     Yes          No
Set         {,}           No           Yes          No
Dict        {k:v,k:v}     by key       Yes          No
</pre>

Search is faster for set and dict because they are hashed instead of sequenced and thus independent of size. set和dict的搜索速度更快,因为它们是经过哈希处理而不是排序,因此与大小无关。 Tuple and list are same except tuple is immutable with fewer methods than list, thus it doesn't support item assignment to alter its content. 元组和列表是相同的,除了元组是不可变的,方法少于列表,因此它不支持项目分配来改变其内容。 But two tuples can be concatenated to achieve "append" functionality, ie t1 += t2 . 但是可以连接两个元组以实现“附加”功能,即t1 += t2

Since only immutable sequence types support hash(), list, set and dict cannot be used as a dict key. 由于只有不可变序列类型支持hash(),因此list,set和dict不能用作dict键。 This can be easily seen below where 'a' is a dict sequence which contains hetero immutable key types of int, float, str, range and tuple: 这可以在下面很容易地看到,其中'a'是一个dict序列,它包含int,float,str,range和tuple的异类不可变键类型:

>>> a
{range(2, 5, 2): 'range', 3: 15, 4.5: 16, 'llmjxm': 'c', -555: 666, -4.5: -25, (5, 6, 7): 'blue', 'abc3': 215, (1, 2, 3): 'red'}
>>> for item in a.keys():
...     print(item, '\t\t==>>', a[item])
... 
range(2, 5, 2)      ==>> range
3       ==>> 15
4.5         ==>> 16
llmjxm      ==>> c
-555        ==>> 666
-4.5        ==>> -25
(5, 6, 7)       ==>> blue
abc3        ==>> 215
(1, 2, 3)       ==>> red
>>> 

whereas a key of mutable type will result in TypeError: 而可变类型的键将导致TypeError:

>>> a[{5}] = 56
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> a[[5]] = 56
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> a[{5:6}] = 56
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> a[-555] = 666
>>> 

Refer to link1 and link2 for more details. 有关更多详细信息,请参阅link1link2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM