Python学习笔记——元组、列表和字典的使用笔记
最近开始学习python语言,所以在学习中做了一些记录,这次讲的是元组、列表和字典的基础操作和区别,至于代码都用图片是因为,看过复制了不如自己动手敲几遍的熟,直接在交互模式下进行即可。
元组
内存存储不同,标签指向不同
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151412317.png"></a>
元组定义了就无法修改:
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151546777.png"></a>
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151602824.png"></a>
列表
我们来定义一个列表,列表使用的是[]中括号
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151622908.png"></a>
由内存存储位置相同我们可以发现为同一个,并不是修改值得指向,即列表可以修改
在列表中,我们同样可以使用索引或切片来得到相应的值
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151637946.png"></a>
列表和元组最大的区别就是,元组定义了就不能修改,但列表可以修改
修改的方法如下:
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151653848.png"></a>
同样如果想向列表中增加一个值,那我们可以调用List.append()方法
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151707910.png"></a>
而如果需要删除我们可以使用List.remove()来删除对应的值
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151725532.png"></a>
当然我们也可以通过以下这两种方法删除
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151738474.png"></a>
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151753155.png"></a>
字典
与之前不同,首先字典使用的是无序的哈希存储,且存储是使用键值对进行存储
定义一个字典的方法如下,使用的是{}花括号
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151811156.png"></a>
定义完我们可以查看我们可以发现并不是按照创建顺序排列,这也证明了字典是无序的
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151826308.png"></a>
前面元组和列表的取值都需要使用索引,比较生涩,现在我们来看看字典取值的方法
直接输入查找的键,找到相应的值
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151844995.png"></a>
我们也可以使用变量来定义,如下定义一个变量,再用变量定义相应的值
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151901479.png"></a>
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151915411.png"></a>
字典里修改与增加相对简单,比较直接
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151930702.png"></a>
删除方面,我们可以用到dic.pop()来删除并返回值
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151943114.png"></a>
同样的我们可以使用系统函数del()删除
<a target="_blank" href="http://blog.51cto.com/attachment/201308/151955498.png"></a>
使用dic.clear()可以清空字典里的数据
<a target="_blank" href="http://blog.51cto.com/attachment/201308/152007648.png"></a>
使用del(dic)可以直接删除该字典
<a target="_blank" href="http://blog.51cto.com/attachment/201308/152019483.png"></a>
本文转自 leyex 51CTO博客,原文链接:http://blog.51cto.com/leyex/1270986