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