您的位置:首页 > 编程语言 > Python开发

python 里list, tuple, set, dict的异同

2015-09-08 10:09 483 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/pilicurg/article/details/48287195

list和tuple

list和tuple都是sequence的一种,是有序列表,其内置的方法都相似,

>>> lst = [1, 2, 3, 4, 5]
>>> tpl = (1, 2, 3, 4, 5)

比如支持in运算,

>>> 1 in lst
True
>>> 1 in tpl
True
>>>

元素有坐标,

>>> lst.index(2)
1
>>> tpl.index(2)
1
>>>

支持index

>>> lst[3]
4
>>> tpl[3]
4
>>>

支持slicing

>>> lst[2:4]
[3, 4]
>>> tpl[2:4]
(3, 4)
>>>

list和tuple的区别:list是mutable的对象,内容可以更改,tuple则不是,所以是hashable的。关于mutable和hashable的概念,可以参考Python 里 immutable和hashable的概念
所以,一些list有的方法,在tuple里就不能实现:

>>> lst.append(6)
>>> lst
[1, 2, 3, 4, 5, 6]
>>> tpl.append(6)

Traceback (most recent call last):
File "", line 1, in
tpl.append(6)
AttributeError: 'tuple' object has no attribute 'append'
>>>
>>> lst.pop()
6
>>> tpl.pop()

Traceback (most recent call last):
File "", line 1, in
tpl.pop()
AttributeError: 'tuple' object has no attribute 'pop'
>>>

set和dict

set和dict的都是无序列表,没有index的概念。

原文链接:http://www.lfhacks.com/tech/list-tuple-set-dict

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: