理解Python中列表,元组,字典,集合里的一些坑

基础知识:理解Python中列表,元组,字典,集合的区别_Yeoman92的博客-CSDN博客_python 字典元组

列表对象不能越界访问

越界访问

In [1]: list = [1,2,3]
In [2]: list[4]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-2-853c8927f3be> in <module>
----> 1 list[4]

IndexError: list index out of range

List对象无法访问不存在的对象

In [3]: list.get(4)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-d60185548bd4> in <module>
----> 1 list.get(4)

AttributeError: 'list' object has no attribute 'get'

因此List对象的:

append() 追加 remove(3) 删除值为3的(首个) list[0] = 'new'
insert(2, 'a') 插入 pop() 删除最后一个
extend(list2) list1链接list2

显然,append和pop就可以实现一个栈,栈顶在list尾;

字典可以访问不存在的元素

In [21]: dist
Out[21]: {(1, 2, 'a', 4, '5', 6): 22}

In [22]: dist.get('aaa')

无输出,或输出为None

元组(Tuple)是只读的

元组和列表在结构上没有什么区别,唯一的差异在于元组是只读的,不能修改;

In [12]: tuple1 = (1,2,'a',4,'5',6)

In [13]: tuple1
Out[13]: (1, 2, 'a', 4, '5', 6)

也就是说元组无法增、删、改,只有查的功能;因为字典的key也是只读的,所以元组也可以作为key:

In [17]: dist = {tuple1:22}

In [18]: dist[(1, 2, 'a', 4, '5', 6)]
Out[18]: 22
posted @ 2022-04-19 18:11  KpHang  阅读(108)  评论(0编辑  收藏  举报