一,List:列表python
python內置的一種數據類型是列表:list.list是一種有序的數據集合,能夠隨意的添加和刪除其中的數據。好比列出班裏全部的同窗的名字,列出全部工廠員工的工號等都是能夠用到列表的,如下是python列表的演示代碼:算法
1 >>> list1 = ['zhangxueyou','liudehua','wanglijuan','liming','shabie'] 2 >>> list1 3 ['zhangxueyou', 'liudehua', 'wanglijuan', 'liming', 'shabie'] 4 >>> list2 = [000001,000002,000003,000004,000005,000006] 5 >>> list2 6 [1, 2, 3, 4, 5, 6] 7 >>>
變量list1,list2都是一個列表的實例,可使用len()函數得到列表的長度(字典中的元素的個數):數組
1 >>> list1 = ['zhangxueyou','liudehua','wanglijuan','liming','shabie'] 2 >>> list1 3 ['zhangxueyou', 'liudehua', 'wanglijuan', 'liming', 'shabie'] 4 >>> list2 = [000001,000002,000003,000004,000005,000006] #其實這裏面寫成字符串更合適 5 >>> list2 6 [1, 2, 3, 4, 5, 6] 7 >>> len(list1) 8 5 9 >>> len(list2) 10 6 11 >>>
可使用索引來引用列表中的元素,注意:列表中的索引是從0開始的,而且在列表中還支持負索引,實例以下:安全
1 >>> list1[0] 2 'zhangxueyou' 3 >>> list1[2] 4 'wanglijuan' 5 >>> list2[1] 6 2 7 >>> list1[-1] 8 'shabie' 9 >>> list2[-2] #這就是負索引的實例 10 5 11 >>>
當訪問的下標越界的時候就會報Index error錯:app
1 >>> list1[78] 2 Traceback (most recent call last): 3 File "<stdin>", line 1, in <module> 4 IndexError: list index out of range 5 >>>
因此,記得在操做python的列表的時候不要越界,記得最後一個元素的索引是:len(list1)-1.函數
當你要取得最後一個元素的時候你除了記住索引以外還有一個更機智的辦法即便使用python的負索引的方法:spa
1 >>> list1[len(list1)-1] 2 'shabie' 3 >>> list1[-1] 4 'shabie' 5 >>>
list是一個能夠變的有序列表,所以能夠往你本身的列表中添加和刪除元素:在末尾添加元素用的是append()方法,在指定的位置插入元素使用的是insert()方法。命令行
1 #在列表末尾追加元素 2 >>> list1.append('xijinping') 3 >>> list1 4 ['zhangxueyou', 'liudehua', 'wanglijuan', 'liming', 'shabie', 'xijinping'] 5 >>> list2.append(7) 6 >>> list2 7 [1, 2, 3, 4, 5, 6, 7] 8 >>> 9 #也能夠在指定的位置上添加元素 10 ... 11 >>> list1.insert(1,'luoting') 12 >>> list1 13 ['zhangxueyou', 'luoting', 'liudehua', 'wanglijuan', 'liming', 'shabie', 'xijinping'] 14 >>> list2.insert(0,8) 15 >>> list2 16 [8, 1, 2, 3, 4, 5, 6, 7] 17 >>>
在列表中刪除元素:刪除末尾的元素使用的是pop()方法,刪除指定位置的元素使用pop(i),其中i是索引下標,指針
1 >>> list1 2 ['zhangxueyou', 'luoting', 'liudehua', 'wanglijuan', 'liming', 'shabie', 'xijinping'] 3 >>> list1.pop() 4 'xijinping' 5 >>> list1 6 ['zhangxueyou', 'luoting', 'liudehua', 'wanglijuan', 'liming', 'shabie'] 7 >>> 8 >>> list1.pop(0) 9 'zhangxueyou' 10 >>> list1 11 ['luoting', 'liudehua', 'wanglijuan', 'liming', 'shabie'] 12 >>> list2.pop() 13 7 14 >>> list2 15 [9, 8, 1, 2, 3, 4, 5, 6] 16 >>> list2.pop(0) 17 9 18 >>> list2 19 [8, 1, 2, 3, 4, 5, 6] 20 >>>
若想替換list中的某個元素,能夠直接把該元素賦值給對應的元素下標便可:code
1 >>> list1 2 ['luoting', 'liudehua', 'wanglijuan', 'liming', 'shabie'] 3 >>> list1[2] = "wyl" 4 >>> list1 5 ['luoting', 'liudehua', 'wyl', 'liming', 'shabie'] 6 >>>
在一個list中能夠有不一樣的數據類型,能夠有字符串類型,整型,或者bool等。
1 >>> list3 = ['baba','mama',123,True] 2 >>> list3 3 ['baba', 'mama', 123, True] 4 >>>
list的元素中也能夠有另一個list,就至關於一個循環的嵌套同樣。
1 >>> list4 = ['wang','wu','luo',['lang','luo','zhang'],'kua'] 2 >>> list4 3 ['wang', 'wu', 'luo', ['lang', 'luo', 'zhang'], 'kua'] 4 >>>
在這個列表中,要取到‘lang’可使用下標索引:list4[3][1],這就至關於c語言中的二維數組,一樣的還能夠層層遞進的寫到三維數組,四維數組等。
1 >>> list4[3][1] 2 3 'luo' 4 5 >>>
若是,一個列表中一個元素都都沒有的話,就是一盒空列表:
1 >>> 2 >>> list5 = [] 3 >>> len(list5) 4 0 5 >>>
python列表的高級應用:
1.用某個固定的值初始化列表:
1 >>> initial_value = 0 2 >>> list_length = 5 3 >>> sample_list = [initial_value for i in range(10)] 4 >>> sample_list = [initial_value]*list_length 5 >>> sample_list 6 [0, 0, 0, 0, 0] 7 >>>
2.產生一個數制遞增的列表:
1 >>> num_inc_list = range(30) 2 >>> num_inc_list 3 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] 4 >>>
3.建立連續的list
L = range(1,5) #即 L=[1,2,3,4],不含最後一個元素
L = range(1, 10, 2) #即 L=[1, 3, 5, 7, 9]
1 >>> L = range(1,5) 2 >>> L 3 [1, 2, 3, 4] 4 >>> L = range(1,20,3) 5 >>> L 6 [1, 4, 7, 10, 13, 16, 19] 7 >>>
list的方法
L.append(var) #追加元素
L.insert(index,var)
L.pop(var) #返回最後一個元素,並從list中刪除之
L.remove(var) #刪除第一次出現的該元素
1 >>> list6 = [1,2,3,4,5,6,4,5,12,65,4] 2 >>> list6 3 [1, 2, 3, 4, 5, 6, 4, 5, 12, 65, 4] 4 >>> list6.remove(4) 5 >>> list6 6 [1, 2, 3, 5, 6, 4, 5, 12, 65, 4] 7 >>>
L.count(var) #該元素在列表中出現的個數
1 >>> list6 = [1,2,3,4,5,6,4,5,12,65,4] 2 >>> list6 3 [1, 2, 3, 4, 5, 6, 4, 5, 12, 65, 4] 4 >>> list6.remove(4) 5 >>> list6 6 [1, 2, 3, 5, 6, 4, 5, 12, 65, 4] 7 >>> 8 >>> list6.count(4) 9 2 10 >>>
L.index(var) #該元素的位置,無則拋異常
1 >>> list6 2 [1, 2, 3, 5, 6, 4, 5, 12, 65, 4] 3 >>> 4 >>> list6.count(4) 5 2 6 >>> list6.index(5) 7 3 8 >>>
L.extend(list6) #追加list6,即合併list到L上
1 >>> L 2 [1, 4, 7, 10, 13, 16, 19] 3 >>> L.extend(list6) 4 >>> L 5 [1, 4, 7, 10, 13, 16, 19, 1, 2, 3, 5, 6, 4, 5, 12, 65, 4] 6 >>>
這裏注意,使用extend函數能夠一次在一個列表中插入任意多個值,而沒必要須每次只使用append()一次一值的插入:
L.sort() #排序
L.reverse() #倒序
1 >>> L 2 [1, 4, 7, 10, 13, 16, 19, 1, 2, 3, 5, 6, 4, 5, 12, 65, 4] 3 >>> L.sort() 4 >>> L 5 [1, 1, 2, 3, 4, 4, 4, 5, 5, 6, 7, 10, 12, 13, 16, 19, 65] 6 >>> L.reverse() 7 >>> L 8 [65, 19, 16, 13, 12, 10, 7, 6, 5, 5, 4, 4, 4, 3, 2, 1, 1] 9 >>>
list 操做符:,+,*,關鍵字del
a[1:] #片斷操做符,用於子list的提取
[1,2]+[3,4] #爲[1,2,3,4]。同extend()
[2]*4 #爲[2,2,2,2]
del L[1] #刪除指定下標的元素
del L[1:3] #刪除指定下標範圍的元素
1 >>> L 2 [65, 19, 16, 13, 12, 10, 7, 6, 5, 5, 4, 4, 4, 3, 2, 1, 1] 3 >>> del L[1] 4 >>> L 5 [65, 16, 13, 12, 10, 7, 6, 5, 5, 4, 4, 4, 3, 2, 1, 1] 6 >>> del L[0:3] 7 >>> L 8 [12, 10, 7, 6, 5, 5, 4, 4, 4, 3, 2, 1, 1] 9 >>>
複製list:
L1 = L #L1爲L的別名,用C來講就是指針地址相同,對L1操做即對L操做。函數參數就是這樣傳遞的
L1 = L[:] #L1爲L的克隆,即另外一個拷貝。
1 >>> l1 = L 2 >>> l1 3 [12, 10, 7, 6, 5, 5, 4, 4, 4, 3, 2, 1, 1] 4 >>> l1 = L[:]
二,Tuple:元組
和列表相似,元組也是一種有序列表,雖然tuple和list很是之相似,可是list初始化以後使能夠改變的,可是,元組一旦初始化以後就不能夠改變。好比,一樣的列出一組人的姓名:
1 >>> tuple1 = ('wuyanl','wangcc','wanggang','dengdacheng') 2 >>> tuple1 3 ('wuyanl', 'wangcc', 'wanggang', 'dengdacheng') 4 >>>
如今tuple1這個tuple不能變了,它也沒有append(),insert()這樣的方法。其餘獲取元素的方法和list是同樣的,你能夠正常地使用tuple1[0]
,tuple1[-1]
,但不能賦值成另外的元素。
不可變的tuple有什麼意義?由於tuple不可變,因此代碼更安全。若是可能,能用tuple代替list就儘可能用tuple。
1 >>> tuple1[0] 2 'wuyanl' 3 >>> tuple1[-1] 4 'dengdacheng' 5 >>> tuple1[4] 6 Traceback (most recent call last): 7 File "<stdin>", line 1, in <module> 8 IndexError: tuple index out of range 9 >>> #一樣越界也是報出一個indexError
tuple的陷阱:當你定義一個tuple時,在定義的時候,tuple的元素就必須被肯定下來,好比:
1 >>> #定義一個空的元組 2 ... 3 >>> t = tuple() 4 >>> t 5 () 6 >>> t = (1,2,3,1) 7 >>> t 8 (1, 2, 3, 1) 9 >>> #定義一個只有一個元素的元組,能夠這樣定義: 10 ... 11 >>> t1 = (123,) 12 >>> t1 13 (123,) 14 >>> #若是你這樣定義你定義的將是123這個元素,而不是一個元組 15 >>> 16 >>> t2 = (123) 17 >>> t2 18 123 19 >>>
定義的不是tuple,是1
這個數!這是由於括號()
既能夠表示tuple,又能夠表示數學公式中的小括號,這就產生了歧義,所以,Python規定,這種狀況下,按小括號進行計算,計算結果天然是1
。
因此,只有1個元素的tuple定義時必須加一個逗號,
,來消除歧義:
Python在顯示只有1個元素的tuple時,也會加一個逗號,
,以避免你誤解成數學計算意義上的括號。
能夠"改變"的tuple:
1 >>> tuple2 = ('aa','bb','cc',['a','b','c'],'dd') 2 >>> tuple2 3 ('aa', 'bb', 'cc', ['a', 'b', 'c'], 'dd') 4 >>> tuple2[3][0] = 'XX' 5 >>> tuple2[3][1] = 'YY' 6 >>> tuple2 7 ('aa', 'bb', 'cc', ['XX', 'YY', 'c'], 'dd') 8 >>> #當一個元組中有列表時是能夠改變元組的值的,其實實質是改變列表的值
1.建立元組:
1 >>> tuple1 = ('wudashen','langdacheng','wangchengcheng') 2 >>> tuple2 = (1,2,3,4,5,6) 3 >>> tuple3 = "a","b","c","d" 4 >>> tuple1 5 ('wudashen', 'langdacheng', 'wangchengcheng') 6 >>> tuple2 7 (1, 2, 3, 4, 5, 6) 8 >>> tuple3 9 ('a', 'b', 'c', 'd') 10 >>>
建立一個空元組時能夠直接建立一個括號,建立一個只有一個元素的元組時,必須在和麪添加一個逗號(,):
>>> >>> tuple4 = () >>> tuple4 () >>> tuple5 = (1,) >>> tuple5 (1,) >>>
元組與字符串相似,下標索引從0開始,能夠進行截取,組合等。
2.訪問元組:
元組可使用下標索引來訪問元組中的值,以下實例:
1 >>> print "tuple1[0]:",tuple1[0] 2 tuple1[0]: wudashen 3 >>> print "tuple1[1:5]",tuple1[1:5] 4 tuple1[1:5] ('langdacheng', 'wangchengcheng') 5 >>> print "tuple2[1:5]",tuple2[1:5] 6 tuple2[1:5] (2, 3, 4, 5) 7 >>>
3.修改元組:
元組中的元素值是不容許修改的,但咱們能夠對元組進行鏈接組合,以下實例:
1 >>> t1 = ('wuyanl','luoting','aimeiyu') 2 >>> t2 = (1,2,3,4,5,6,7,8,9,0) 3 >>> t1 4 ('wuyanl', 'luoting', 'aimeiyu') 5 >>> t2 6 (1, 2, 3, 4, 5, 6, 7, 8, 9, 0) 7 >>> t3 = t1 +t2 8 >>> t3 9 ('wuyanl', 'luoting', 'aimeiyu', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0) 10 >>>
4.刪除元組:
元組中的元素值是不容許刪除的,但咱們可使用del語句來刪除整個元組,以下實例:
1 >>> print t1 2 ('wuyanl', 'luoting', 'aimeiyu') 3 >>> del t1 4 >>> t1 5 Traceback (most recent call last): 6 File "<stdin>", line 1, in <module> 7 NameError: name 't1' is not defined 8 >>>
5.元組運算符:
與字符串同樣,元組之間可使用 + 號和 * 號進行運算。這就意味着他們能夠組合和複製,運算後會生成一個新的元組。
6.元組索引,截取:
由於元組也是一個序列,因此咱們能夠訪問元組中的指定位置的元素,也能夠截取索引中的一段元素,以下所示:
7. 元組的內置函數:
(1),比較兩個元組元素:cmp(tuple1,tuple2)
1 >>> tuple1 2 ('wudashen', 'langdacheng', 'wangchengcheng') 3 >>> tuple2 4 (1, 2, 3, 4, 5, 6) 5 >>> cmp(tuple1,tuple2) 6 1 7 >>> #兩個元組不相等則返回1 8 ... 9 >>> tt1 = (1,2,3) 10 >>> tt1 11 (1, 2, 3) 12 >>> tt2 = (1,2,3) 13 >>> tt2 14 (1, 2, 3) 15 >>> cmp(tt1,tt2) 16 0 17 >>> #兩個元組相等則返回0 18 ... 19 >>>
(2),計算元組的長度:len(tuple1):
1 >>> len(tt1) 2 3 3 >>> len(tt2) 4 3 5 >>> len(tuple1) 6 3 7 >>> len(tuple2) 8 6 9 >>>
(3),返回元組中的最大值:max(tuple2),min(tuple2)
1 >>> 2 >>> max(tt1) 3 3 4 >>> max(tuple1) 5 'wudashen' 6 >>> max(tuple2) 7 6 8 >>> max(tuple3) 9 'd' 10 >>> min(tt1) 11 1 12 >>> min(tuple3) 13 'a' 14 >>> #返回元組中的最小值
(4),將列表轉換成元組:
1 >>> list1 2 ['luoting', 'liudehua', 'wyl', 'liming', 'shabie'] 3 >>> lt = tuple(list1) 4 >>> lt 5 ('luoting', 'liudehua', 'wyl', 'liming', 'shabie') 6 >>>
元組的知識就先介紹到這裏,如下詳細的來講一下重頭戲--字典:
三,Dict:字典
Python內置了字典:dict的支持,dict全稱dictionary,在其餘語言中也稱爲map,使用鍵-值(key-value)存儲,具備極快的查找速度。
在這裏能夠舉一個例子,假如你經過列表來查看工人的名字和對應的工資的話,在這裏你須要設置兩個列表,一個用於存儲名字,一個用於存儲工資:
1 >>> name = ['zhangsan','lisi','wangwu','doubie'] 2 >>> name 3 ['zhangsan', 'lisi', 'wangwu', 'doubie'] 4 >>> salary = [20000,30000,200000,123000] 5 >>> salary 6 [20000, 30000, 200000, 123000] 7 >>>
給定一個名字,要查找對應的成績,就先要在name中找到對應的位置,再從salary取出對應的成績,list越長,耗時越長。
若是用dict實現,只須要一個「名字」-「薪水」的對照表,直接根據名字查找成績,不管這個表有多大,查找速度都不會變慢。
用Python寫一個dict以下:
1 >>> dict1 = {'zhangsan':30000,'lisi':321000,'wanger':123654,'wangwu':123878} 2 >>> dict1 3 {'lisi': 321000, 'zhangsan': 30000, 'wanger': 123654, 'wangwu': 123878} 4 >>>
爲何dict查找速度這麼快?由於dict的實現原理和查字典是同樣的。假設字典包含了1萬個漢字,咱們要查某一個字,一個辦法是把字典從第一頁日後翻,直到找到咱們想要的字爲止,這種方法就是在list中查找元素的方法,list越大,查找越慢。
第二種方法是先在字典的索引表裏(好比部首表)查這個字對應的頁碼,而後直接翻到該頁,找到這個字,不管找哪一個字,這種查找速度都很是快,不會隨着字典大小的增長而變慢。
dict就是第二種實現方式,給定一個名字,好比'zhangsan'
,dict在內部就能夠直接計算出zhangsanl
對應的存放成績的「頁碼」,也就是30000這個數字存放的內存地址,直接取出來,因此速度很是快。
你能夠猜到,這種key-value存儲方式,在放進去的時候,必須根據key算出value的存放位置,這樣,取的時候才能根據key直接拿到value。
把數據放入dict的方法,除了初始化時指定外,還能夠經過key放入:
1 >>> dict1 = {'zhangsan':30000,'lisi':321000,'wanger':123654,'wangwu':123878} 2 >>> dict1 3 {'lisi': 321000, 'zhangsan': 30000, 'wanger': 123654, 'wangwu': 123878} 4 >>> dict1['zhangsan'] 5 30000 6 >>> dict1['wangwu'] 7 123878 8 >>> dict1['lisi'] 9 321000 10 >>>
油魚一個key只能對應一個值,所以,假若你屢次對同一個key賦值的話,之前賦的值會被覆蓋掉。
1 >>> dict1 2 {'lisi': 321000, 'zhangsan': 30000, 'wanger': 123654, 'wangwu': 123878} 3 >>> dict1['zhangsan'] = 1000000 4 >>> dict1 5 {'lisi': 321000, 'zhangsan': 1000000, 'wanger': 123654, 'wangwu': 123878} 6 >>> dict1['zhangsan'] = 100 7 >>> dict1 8 {'lisi': 321000, 'zhangsan': 100, 'wanger': 123654, 'wangwu': 123878} 9 >>>
若是你想賦值的key不存在就會報錯:
1 >>> dict1['xidada'] = 4563221 2 >>> dict1 3 {'lisi': 321000, 'xidada': 4563221, 'zhangsan': 100, 'wanger': 123654, 'wangwu': 123878} 4 >>> dict1['wangcc'] 5 Traceback (most recent call last): 6 File "<stdin>", line 1, in <module> 7 KeyError: 'wangcc' 8 >>> dict1['wyl'] = 888888 9 >>> dict1 10 {'wanger': 123654, 'xidada': 4563221, 'lisi': 321000, 'wangwu': 123878, 'wyl': 888888, 'zhangsan': 100} 11 >>>
由以上的代碼能夠看出,當你的字典中沒有這個key,可是你還給這個key賦值的話,是不會報錯的,而且你的值能夠插入這個字典中,可是假如你訪問一個沒有的key值,就會報出一個KeyError,
所以,要想判斷key值是否存在,能夠有兩個方法。
方法一:使用in語句判斷:
1 >>> dict1 2 {'wanger': 123654, 'xidada': 4563221, 'lisi': 321000, 'wangwu': 123878, 'wyl': 888888, 'zhangsan': 100} 3 >>> 'zhangsan' in dict1 4 True 5 >>> 'liudehua' in dict1 6 False 7 >>> dict1
方法二:使用dict提供的get()方法,若key值不存在就返回None或者本身指定的返回值:
1 >> dict1 2 {'wanger': 123654, 'xidada': 4563221, 'lisi': 321000, 'wangwu': 123878, 'wyl': 888888, 'zhangsan': 100} 3 >>> dict1.get('zhangdada','not any') 4 'not any' 5 >>> #使用本身定義的返回值
1 >>> dict1 2 {'wanger': 123654, 'xidada': 4563221, 'lisi': 321000, 'wangwu': 123878, 'wyl': 888888, 'zhangsan': 100} 3 >>> 4 >> dict1.get('zhangsan') 5 100 6 >>> dict1.get('xielaoda') 7 >>> #什麼都沒有返回(NONE) 8 ... 9 >>>
注意:返回None的時候Python的交互式命令行不顯示結果。
和列表和元組相似,當你要刪除一個字典值的時候,你可使用pop(key)的方法達到刪除字典元素的目的:
1 >>> dict1 2 {'wanger': 123654, 'xidada': 4563221, 'lisi': 321000, 'wangwu': 123878, 'wyl': 888888, 'zhangsan': 100} 3 >>> dict1.pop('wanger') 4 123654 5 >>> dict1 6 {'xidada': 4563221, 'lisi': 321000, 'wangwu': 123878, 'wyl': 888888, 'zhangsan': 100} 7 >>> dict1.pop('xidada') 8 4563221 9 >>> dict1 10 {'lisi': 321000, 'wangwu': 123878, 'wyl': 888888, 'zhangsan': 100} 11 >>>
注意,dict內部存放的順序和key放入的順序是沒有關係的。
和list比較,dict有如下幾個特色:
而list相反:
因此,dict是用空間來換取時間的一種方法。
dict能夠用在須要高速查找的不少地方,在Python代碼中幾乎無處不在,正確使用dict很是重要,須要牢記的第一條就是dict的key必須是不可變對象。
這是由於dict根據key來計算value的存儲位置,若是每次計算相同的key得出的結果不一樣,那dict內部就徹底混亂了。這個經過key計算位置的算法稱爲哈希算法(Hash)。
要保證hash的正確性,做爲key的對象就不能變。在Python中,字符串、整數等都是不可變的,所以,能夠放心地做爲key。而list是可變的,就不能做爲key:
字典的高級應用:
1 >>> dict2 = {'a':1,'b':2,'c':3} 2 >>> dict2 3 {'a': 1, 'c': 3, 'b': 2} 4 >>> dict3 = dict2 5 >>> dict3 6 {'a': 1, 'c': 3, 'b': 2} 7 >>> del dict2['a'] #刪除key爲'a'的條目 8 >>> dict2 9 {'c': 3, 'b': 2} 10 >>> dict2.clear() 11 >>> dict2.clear() 12 >>> dict2.clear()#清空字典; 13 >>> dict2 14 {} 15 >>> del dict2 #直接刪除整個字典 16 >>> dict2 17 Traceback (most recent call last): 18 File "<stdin>", line 1, in <module> 19 NameError: name 'dict2' is not defined 20 >>> #刪除以後再輸出dict2字典確實出錯了 21 ... 22 >>>
字典鍵的特性:
(1),在字典中同一個key不能夠出現兩次或以上:
1 >>> dict4 = {'name':123,'name':1236} 2 >>> dict4 3 {'name': 1236} 4 >>> #兩次設置name可是隻顯示一次
(2),鍵必須不可變,因此能夠用數,字符串或元組充當,因此用列表就不行,以下實例:換言之就是
1 >>> dict4 = {'name1':123,'name2':1236,'name3':1} 2 >>> dict4 3 {'name2': 1236, 'name3': 1, 'name1': 123} 4 >>>
字典的內置函數和方法:
(1),字典中的cmp函數用於比較兩個字典是否是相等的:
1 >>> dic1 = {'a':1,'b':2,'c':3} 2 >>> dic2 = dic1 3 >>> dic3 = {'e':3,'r':5,'y':7} 4 >>> cmp(dic1,dic2) 5 0 6 >>> cmp(dic2,dic3) 7 -1 8 >>> #兩個字典比較,若是相同就返回0 不然返回-1 9 ... #cmp函數就是用於比較兩個字典是否是相等的字典內置函數
(2),len(dict):計算字典元素個數,即鍵的總數。
1 >>> len(dic1) 2 3 3 >>> len(dic2) 4 3 5 >>> len(dic3) 6 3 7 >>> len(dict1) 8 4 9 >>>
(3),str(dict):輸出字典可打印的字符串表示。
1 >>> str(dic1) 2 "{'a': 1, 'c': 3, 'b': 2}" 3 >>> str(dic2) 4 "{'a': 1, 'c': 3, 'b': 2}" 5 >>> str(dic3) 6 "{'y': 7, 'r': 5, 'e': 3}" 7 >>> str(dict1) 8 "{'lisi': 321000, 'wangwu': 123878, 'wyl': 888888, 'zhangsan': 100}" 9 >>>
(4),type(variable):返回輸入的變量類型,若是變量是字典就返回字典類型。
1 >>> type(dic1) 2 <type 'dict'> 3 >>> type(dic2) 4 <type 'dict'> 5 >>> type(dict1) 6 <type 'dict'> 7 >>>
Python字典包含了如下內置方法:
一、radiansdict.clear():刪除字典內全部元素
1 >>> dic1 2 {'a': 1, 'c': 3, 'b': 2} 3 >>> dic1.clear() 4 >>> dic1 5 {} 6 >>>
二、radiansdict.copy():返回一個字典的淺複製
1 >>> dic3 2 {'y': 7, 'r': 5, 'e': 3} 3 >>> dic3.copy() 4 {'y': 7, 'r': 5, 'e': 3} 5 >>> dic3 6 {'y': 7, 'r': 5, 'e': 3} 7 >>>
三、radiansdict.fromkeys():建立一個新字典,以序列seq中元素作字典的鍵,val爲字典全部鍵對應的初始值
四、radiansdict.get(key, default=None):返回指定鍵的值,若是值不在字典中返回default值
1 >>> dict1.get('zhangxueyou','not any') 2 'not any' 3 >>>
五、radiansdict.has_key(key):若是鍵在字典dict裏返回true,不然返回false
1 >>> dict1 2 {'lisi': 321000, 'wangwu': 123878, 'wyl': 888888, 'zhangsan': 100} 3 >>> dict1.has_key('wangwu') 4 True 5 >>> dict1.has_key('wang') 6 False 7 >>>
六、radiansdict.items():以列表返回可遍歷的(鍵, 值) 元組數組
1 >>> dict1.items() 2 [('lisi', 321000), ('wangwu', 123878), ('wyl', 888888), ('zhangsan', 100)] 3 >>>
七、radiansdict.keys():以列表返回一個字典全部的鍵
1 >>> list2 = {'a':1,'b':2,'c':3,'d':4} 2 >>> list2 3 {'a': 1, 'c': 3, 'b': 2, 'd': 4} 4 >>> list2.keys() 5 ['a', 'c', 'b', 'd'] 6 >>>
八、radiansdict.setdefault(key, default=None):和get()相似, 但若是鍵不已經存在於字典中,將會添加鍵並將值設爲default
九、radiansdict.update(dict2):把字典dict2的鍵/值對更新到dict裏
十、radiansdict.values():以列表返回字典中的全部值
1 >>> list2 2 {'a': 1, 'c': 3, 'b': 2, 'd': 4} 3 >>> list2.values() 4 [1, 3, 2, 4] 5 >>>
四,set
原本,打算只講一下字典,元組,列表的一些基本用法,可是如今擴展探討一下python中的set的用法:
set和dict相似,也是一組key的集合,但不存儲value。因爲key不能重複,因此,在set中,沒有重複的key。
要建立一個set,須要提供一個list做爲輸入集合:
1 >>> s = set([1,2,3,4,5,6,7,8,9]) 2 >>> s 3 set([1, 2, 3, 4, 5, 6, 7, 8, 9]) 4 >>>
注意,傳入的參數[1, 2, 3]
是一個list,而顯示的set([1, 2, 3])
只是告訴你這個set內部有1,2,3這3個元素,顯示的[]不表示這是一個list。
重複元素在set中自動被過濾:
1 >>> s = set([1,2,3,4,5,6,7,8,9]) 2 >>> s 3 set([1, 2, 3, 4, 5, 6, 7, 8, 9]) 4 >>> s = set([1,2,3,4,5,6,7,8,9,1,2,3,3,4,5,6,7,89,97,7]) 5 >>> s 6 set([1, 2, 3, 4, 5, 6, 7, 8, 9, 97, 89]) 7 >>>
這一點,有點想數學中的集合的互異性相似。
在此,你還可使用add()方法添加元素到set找你剛,當你重複添加的時候是不會報錯的,只是不會在set中看到重複的值,它會本身過虐掉的。
1 >>> s 2 set([1, 2, 3, 4, 5, 6, 7, 8, 9, 97, 89]) 3 >>> s.add(100) 4 >>> s.add(100) 5 >>> s.add(123) 6 >>> s.add(321) 7 >>> s 8 set([1, 2, 3, 4, 5, 6, 7, 8, 9, 321, 97, 89, 123, 100]) 9 >>>
若你想刪除set中的值,你可使用方法remove(key)達到你想要的效果。
1 >>> s 2 set([1, 2, 3, 4, 5, 6, 7, 8, 9, 321, 97, 89, 123]) 3 >>> s.remove(1) 4 >>> s 5 set([2, 3, 4, 5, 6, 7, 8, 9, 321, 97, 89, 123]) 6 >>>
set能夠當作數學意義上的無序和無重複元素的集合,所以,兩個set能夠作數學意義上的交集、並集等操做:
1 >>> s1 = set([1,2,3,4,5,6,7,8,9]) 2 >>> s1 3 set([1, 2, 3, 4, 5, 6, 7, 8, 9]) 4 >>> s2 = set([4,2,3,6]) 5 >>> s2 6 set([2, 3, 4, 6]) 7 >>> s1 & s2 8 set([2, 3, 4, 6]) 9 >>> s1 | s2 10 set([1, 2, 3, 4, 5, 6, 7, 8, 9]) 11 >>>
set和dict的惟一區別僅在於沒有存儲對應的value,可是,set的原理和dict同樣,因此,一樣不能夠放入可變對象,由於沒法判斷兩個可變對象是否相等,也就沒法保證set內部「不會有重複元素」。試試把list放入set,看看是否會報錯。