Python容器:列表、元組、字典與集合
列表:
1.列表 的創建
使用[ ] 或者 list()創建列表:empty_list = [ ] 或者 empty_list= list()
使用list()將其他數據類型轉換成列表 方括號[ ]列表 圓括號( )元組
>>> list('cat') ['c', 'a', 't']
使用[offset]獲取元素
>>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> marxes[0] 'Groucho'
包含列表的列表: 列表可以包含各種類型的元素,包括其他列表
>>> small_birds = ['hummingbird', 'finch'] >>> extinct_birds = ['dodo', 'passenger pigeon', 'Norwegian Blue'] >>> carol_birds = [3, 'French hens', 2, 'turtledoves'] >>> all_birds = [small_birds, extinct_birds, 'macaw', carol_birds]
=================================================================
>>> all_birds [['hummingbird', 'finch'], ['dodo', 'passenger pigeon', 'Norwegian Blue'], 'macaw', [3, 'French hens', 2, 'turtledoves']]
獲取列表中字子列表的元素:
>>> all_birds[1][0] 'dodo'
2、列表操作
使用[offset]修改元素
>>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> marxes[2] = 'Wanda' >>> marxes ['Groucho', 'Chico', 'Wanda']
指定范圍並使用切片提取元素
>>> marxes = ['Groucho', 'Chico,' 'Harpo'] >>> marxes[0:2] ['Groucho', 'Chico']
使用append()添加元素至尾部
>>> marxes.append('Zeppo') >>> marxes ['Groucho', 'Chico', 'Harpo', 'Zeppo']
使用extend()或+=合並列表
>>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> others = ['Gummo', 'Karl'] >>> marxes.extend(others) >>> marxes ['Groucho', 'Chico', 'Harpo', 'Zeppo', 'Gummo', 'Karl']
使用insert()在指定位置插入元素
>>> marxes.insert(3, 'Gummo') >>> marxes ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo'] >>> marxes.insert(10, 'Karl') >>> marxes ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo', 'Karl']
使用del刪除指定位置的元素
del marxes[-1]
使用remove()刪除具有指定值的元素
>>> marxes.remove('Gummo')
使用pop()獲取並刪除指定位置的元素
>>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> marxes.pop() 'Zeppo' >>> marxes ['Groucho', 'Chico', 'Harpo'] >>> marxes.pop(1) 'Chico' >>> marxes ['Groucho', 'Harpo']
使用index()查詢具有特定值的元素位置
>>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> marxes.index('Chico') 1
使用in判斷值是否存在
>>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> 'Groucho' in marxes
使用count()記錄特定值出現的次數:使用count() 可以記錄某一個特定值在列表中出現的次數
>>> marxes.count('Harpo')
使用join()轉換為字符串
>>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> ', '.join(marxes) 'Groucho, Chico, Harpo'
使用sort()重新排列元素:列表方法sort() 會對原列表進行排序,改變原列表內容;
通用函數sorted() 則會返回排好序的列表副本,原列表內容不變。
使用len()獲取長度
>>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> len(marxes) 3
使用=賦值,使用copy()復制
>>> a = [1, 2, 3] >>> a [1, 2, 3] >>> b = a >>> b [1, 2, 3] >>> a[0] = 'surprise' >>> a ['surprise', 2, 3]
元組和列表:
在許多地方都可以用元組代替列表,但元組的方法函數與列表相比要少一些——元組沒有
append()、insert(),等等——因為一旦創建元組便無法修改。既然列表更加靈活,那為
什么不在所有地方都使用列表呢?原因如下所示:
• 元組占用的空間較小
• 你不會意外修改元組的值
• 可以將元組用作字典的鍵(詳見3.4 節)
• 命名元組(詳見第6 章“命名元組”小節)可以作為對象的替代
• 函數的參數是以元組形式傳遞的
字典:
字典新建:
>>> empty_dict = {}
使用dict() 轉換:
>>> lol = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ] >>> dict(lol) {'c': 'd', 'a': 'b', 'e': 'f'}
字典中元素的順序是無關緊要的,實際存儲順序可能取決於你添加元
素的順序。
可以對任何包含雙值子序列的序列使用dict(),下面是其他例子。
包含雙值元組的列表:
>>> lot = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ] >>> dict(lot) {'c': 'd', 'a': 'b', 'e': 'f'}
包含雙值列表的元組:
>>> tol = ( ['a', 'b'], ['c', 'd'], ['e', 'f'] ) >>> dict(tol) {'c': 'd', 'a': 'b', 'e': 'f'}
雙字符的字符串組成的列表:
>>> los = [ 'ab', 'cd', 'ef' ] >>> dict(los) {'c': 'd', 'a': 'b', 'e': 'f'}
雙字符的字符串組成的元組:
>>> tos = ( 'ab', 'cd', 'ef' ) >>> dict(tos) {'c': 'd', 'a': 'b', 'e': 'f'}
使用[key]添加或修改元素
>>> pythons = { ... 'Chapman': 'Graham', ... 'Cleese': 'John', ... 'Idle': 'Eric', ... 'Jones': 'Terry', ... 'Palin': 'Michael', ... } >>> pythons {'Cleese': 'John', 'Jones': 'Terry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric'} #使用[KEY]值,添加元素 >>> pythons['Gilliam'] = 'Gerry' >>> pythons {'Cleese': 'John', 'Gilliam': 'Gerry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'} #使用[KEY]值,修改元素 >>> pythons['Gilliam'] = 'Terry' >>> pythons {'Cleese': 'John', 'Gilliam': 'Terry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'}
使用update()合並字典
>>> pythons = { #定義一個字典 ... 'Chapman': 'Graham', ... 'Cleese': 'John', ... 'Gilliam': 'Terry', ... 'Idle': 'Eric', ... 'Jones': 'Terry', ... 'Palin': 'Michael', ... } >>> pythons {'Cleese': 'John', 'Gilliam': 'Terry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'} #定義另一個字典 >>> others = { 'Marx': 'Groucho', 'Howard': 'Moe' } #使用.update(),合並字典 >>> pythons.update(others) >>> pythons {'Cleese': 'John', 'Howard': 'Moe', 'Gilliam': 'Terry', 'Palin': 'Michael', 'Marx': 'Groucho', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'}
使用del刪除具有指定鍵的元素
>>> del pythons['Marx'] #刪除字典中的元素 >>> pythons {'Cleese': 'John', 'Howard': 'Moe', 'Gilliam': 'Terry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'} >>> del pythons['Howard'] >>> pythons {'Cleese': 'John', 'Gilliam': 'Terry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'}
使用clear()刪除所有元素
使用clear(),或者給字典變量重新賦值一個空字典({})可以將字典中所有元素刪除:
>>> pythons.clear() >>> pythons {} >>> pythons = {} >>> pythons {}
使用in判斷是否存在
>>> pythons = {'Chapman': 'Graham', 'Cleese': 'John', 'Jones': 'Terry', 'Palin': 'Michael'} #測試XXX是否在字典中 >>> 'Chapman' in pythons True
使用[key]獲取元素
>>> pythons['Cleese'] 'John'
keys()、values()、items()、=、copy()
使用keys()獲取所有鍵、使用values()獲取所有值、使用items()獲取所有鍵值、使用=賦值,使用copy()復制
>>> signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'} >>> signals.keys() #使用keys()獲取所有鍵 dict_keys(['green', 'yellow', 'red']) >>> list( signals.keys() ) ['green', 'yellow', 'red'] >>> list( signals.values() )#使用values()獲取所有值 ['go', 'go faster', 'smile for the camera'] >>> list( signals.items() ) #使用items()獲取所有鍵值對 [('green', 'go'), ('yellow', 'go faster'), ('red', 'smile for the camera')] >>> save_signals = signals #使用=賦值 >>> signals['blue'] = 'confuse everyone' >>> save_signals {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera', 'blue': 'confuse everyone'} #對字典內容進行的修改會反映到所有與之相關聯的變量名上 #================================= # 使用copy()復制 >>> signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'} >>> original_signals = signals.copy() >>> signals['blue'] = 'confuse everyone' >>> signals {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera', 'blue': 'confuse everyone'} >>> original_signals {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}
集合:
1、使用set()創建集合
>>> empty_set = set() >>> empty_set set() >>> even_numbers = {0, 2, 4, 6, 8} >>> even_numbers {0, 8, 2, 4, 6} >>> odd_numbers = {1, 3, 5, 7, 9} >>> odd_numbers {9, 3, 1, 5, 7} #集合中的元素是無序的
2、使用set()將其他類型轉換為集合
>>> set( 'letters' ) {'l', 'e', 't', 'r', 's'} #轉換以后,重復的元素會去重
用列表建立集合:
>>> set( ['Dasher', 'Dancer', 'Prancer', 'Mason-Dixon'] ) {'Dancer', 'Dasher', 'Prancer', 'Mason-Dixon'}
再試試元組:
>>> set( ('Ummagumma', 'Echoes', 'Atom Heart Mother') ) {'Ummagumma', 'Atom Heart Mother', 'Echoes'} #使用元組建立集合
當字典作為參數傳入set() 函數時,只有鍵會被使用:
>>> set( {'apple': 'red', 'orange': 'orange', 'cherry': 'red'} ) {'cherry', 'apple', 'orange'}
使用in測試值是否存在
>>> drinks = { 'martini': {'vodka', 'vermouth'}, 'black russian': {'vodka', 'kahlua'}, 'white russian': {'cream', 'kahlua', 'vodka'}, 'manhattan': {'rye', 'vermouth', 'bitters'}, 'screwdriver': {'orange juice', 'vodka'} } >>> for name, contents in drinks.items(): # 使用IN值測試值是否存在 if 'vodka' in contents : # 使用IN值測試值是否存在 print(name) martini black russian white russian screwdriver
>>> for name, contents in drinks.items(): if 'vodka' in contents and not ('vermouth' in contents or 'cream' in contents): print(name) black russian screwdriver
合並及運算符
交集運算:& 或者 x.intersection
>>> a = {1,2} >>> b = {3,4} >>> a & b set() >>> a.intersection(b) set()
異或運算
#使用^ 或者symmetric_difference() 可以獲得兩個集合的異或集 >>> a ^ b {1, 3} >>> a.symmetric_difference(b) {1, 3} #使用<= 或者issubset() 可以判斷一個集合是否是另一個集合的子集(第一個集合的所有 元素都出現在第二個集合中): >>> a = {1,3} >>> b = {2,4} >>> c = {1} >>> d = {2} >>> a <= b False >>> b <= a False >>> c <= a True >>> c <= b False >>> d <= a False >>> d <= b # 超集與子集正好相反(第二個集合的所有元素都出現在第一個集合中),使用>= 或者 issuperset() 可以進行判斷: >>> a >= b False >>> a >= c True >>> a >=d False # 子集 真子集 >>> a > a False >>> a < a False >>> d > d False >>> d < d False >>> d == d True >>> a >= a True >>> d >= d True >>> a <= a True >>> a < a False >>> a > a False
字典與集合:
用方括號([])創建列表,
使用逗號創建元組(,)
使用花括號({})創建字典
在每一種類型中,都可以通過方括號對單個元素進行訪問:
自定義數據結構:
在創建自定義結構的過程中,唯一的限制來自於內置數據類型本身。
例如:字典的鍵必須為不可變對象,所以列表、字典以及集合都不能作為字典的鍵,但是元組可以作為字典的鍵。