1. 列表、元組操作
列表是我們最以后最常用的數據類型之一,通過列表可以對數據實現最方便的存儲、修改等操作
定義列表
names = ['Alex',"Tenglan",'Eric']
通過下標訪問列表中的元素,下標從0開始計數
>>> names[0] 'Alex' >>> names[2] 'Eric' >>> names[-1] 'Eric' >>> names[-2] #還可以倒著取 'Tenglan'
切片:取多個元素


>>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"] >>> names[1:4] #取下標1至下標4之間的數字,包括1,不包括4 ['Tenglan', 'Eric', 'Rain'] >>> names[1:-1] #取下標1至-1的值,不包括-1 ['Tenglan', 'Eric', 'Rain', 'Tom'] >>> names[0:3] ['Alex', 'Tenglan', 'Eric'] >>> names[:3] #如果是從頭開始取,0可以忽略,跟上句效果一樣 ['Alex', 'Tenglan', 'Eric'] >>> names[3:] #如果想取最后一個,必須不能寫-1,只能這么寫 ['Rain', 'Tom', 'Amy'] >>> names[3:-1] #這樣-1就不會被包含了 ['Rain', 'Tom'] >>> names[0::2] #后面的2是代表,每隔一個元素,就取一個 ['Alex', 'Eric', 'Tom'] >>> names[::2] #和上句效果一樣 ['Alex', 'Eric', 'Tom']
追加


>>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy'] >>> names.append("我是新來的") >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新來的']
插入


>>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新來的'] >>> names.insert(2,"強行從Eric前面插入") >>> names ['Alex', 'Tenglan', '強行從Eric前面插入', 'Eric', 'Rain', 'Tom', 'Amy', '我是新來的']>>> names.insert(5,"從eric后面插入試試新姿勢") >>> names ['Alex', 'Tenglan', '強行從Eric前面插入', 'Eric', 'Rain', '從eric后面插入試試新姿勢', 'Tom', 'Amy', '我是新來的']
修改


>>> names ['Alex', 'Tenglan', '強行從Eric前面插入', 'Eric', 'Rain', '從eric后面插入試試新姿勢', 'Tom', 'Amy', '我是新來的'] >>> names[2] = "該換人了" >>> names ['Alex', 'Tenglan', '該換人了', 'Eric', 'Rain', '從eric后面插入試試新姿勢', 'Tom', 'Amy', '我是新來的']
刪除


>>> del names[2] >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', '從eric后面插入試試新姿勢', 'Tom', 'Amy', '我是新來的'] >>> del names[4] >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新來的'] >>> >>> names.remove("Eric") #刪除指定元素 >>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', '我是新來的'] >>> names.pop() #刪除列表最后一個值 '我是新來的' >>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
擴展


>>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy'] >>> b = [1,2,3] >>> names.extend(b) >>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
拷貝


>>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]>>> name_copy = names.copy() >>> name_copy ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
統計


>>> names ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3] >>> names.count("Amy") 2
排序&翻轉


>>> names ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3] >>> names.sort() #排序 Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: unorderable types: int() < str() #3.0里不同數據類型不能放在一起排序了,擦 >>> names[-3] = '1' >>> names[-2] = '2' >>> names[-1] = '3' >>> names ['Alex', 'Amy', 'Amy', 'Tenglan', 'Tom', '1', '2', '3'] >>> names.sort() >>> names ['1', '2', '3', 'Alex', 'Amy', 'Amy', 'Tenglan', 'Tom']>>> names.reverse() #反轉 >>> names ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']
獲取下標


>>> names ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1'] >>> names.index("Amy") 2 #只返回找到的第一個下標
元組
元組其實跟列表差不多,也是存一組數,只不是它一旦創建,便不能再修改,所以又叫只讀列表
語法
names?
=
?(
"alex"
,
"jack"
,
"eric"
)
它只有2個方法,一個是count,一個是index,完畢。
2. 字符串操作


>>> n3_arg {'name': 'alex', 'age': 33} >>> n3 'my name is {name} and age is {age}' >>> n3.format_map(n3_arg) 'my name is alex and age is 33'>>> n4.ljust(40,"-") 'Hello 2orld-----------------------------' >>> n4.rjust(40,"-") '-----------------------------Hello 2orld'>>> s = "Hello World!" >>> p = str.maketrans("abcdefg","3!@#$%^") >>> s.translate(p) 'H$llo Worl#!>>> b="ddefdsdff_哈哈" >>> b.isidentifier() #檢測一段字符串可否被當作標志符,即是否符合變量命名規則 True
3. 字典操作
字典一種key - value 的數據類型,使用就像我們上學用的字典,通過筆劃、字母來查對應頁的詳細內容。
key-value對
- 特性:
- 無順序
- 去重
- 查詢速度快,比列表快多了
- 比list占用內存多
為什么會查詢速度會快呢?因為他是hash類型的,那什么是hash呢?
哈希算法將任意長度的二進制值映射為較短的固定長度的二進制值,這個小的二進制值稱為哈希值。哈希值是一段數據唯一且極其緊湊的數值表示形式。如果散列一段明文而且哪怕只更改該段落的一個字母,隨后的哈希都將產生不同的值。要找到散列為同一個值的兩個不同的輸入,在計算上是不可能的,所以數據的哈希值可以檢驗數據的完整性。一般用于快速查找和加密算法
dict會把所有的key變成hash 表,然后將這個表進行排序,這樣,你通過data[key]去查data字典中一個key的時候,python會先把這個key hash成一個數字,然后拿這個數字到hash表中看沒有這個數字, 如果有,拿到這個key在hash表中的索引,拿到這個索引去與此key對應的value的內存地址那取值就可以了。
語法:
info = {'stu1101': "TengLan Wu",'stu1102': "LongZe Luola",'stu1103': "XiaoZe Maliya", }
字典的特性:
- dict是無序的
- key必須是唯一的,so 天生去重
增加


>>> info["stu1104"] = "蒼井空" >>> info {'stu1102': 'LongZe Luola', 'stu1104': '蒼井空', 'stu1103': 'XiaoZe Maliya', 'stu1101': 'TengLan Wu'}
修改


>>> info['stu1101'] = "武藤蘭" >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤蘭'}
刪除


>>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤蘭'} >>> info.pop("stu1101") #標準刪除姿勢 '武藤蘭' >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} >>> del info['stu1103'] #換個姿勢刪除 >>> info {'stu1102': 'LongZe Luola'} >>> >>> >>> >>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} #隨機刪除 >>> info.popitem() ('stu1102', 'LongZe Luola') >>> info {'stu1103': 'XiaoZe Maliya'}
查找


>>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} >>> >>> "stu1102" in info #標準用法 True >>> info.get("stu1102") #獲取 'LongZe Luola' >>> info["stu1102"] #同上,但是看下面 'LongZe Luola' >>> info["stu1105"] #如果一個key不存在,就報錯,get不會,不存在只返回None Traceback (most recent call last):File "<stdin>", line 1, in <module> KeyError: 'stu1105'
多級字典嵌套及操作


av_catalog = {"歐美":{"www.youporn.com": ["很多免費的,世界最大的","質量一般"],"www.pornhub.com": ["很多免費的,也很大","質量比yourporn高點"],"letmedothistoyou.com": ["多是自拍,高質量圖片很多","資源不多,更新慢"],"x-art.com":["質量很高,真的很高","全部收費,屌比請繞過"]},"日韓":{"tokyo-hot":["質量怎樣不清楚,個人已經不喜歡日韓范了","聽說是收費的"]},"大陸":{"1024":["全部免費,真好,好人一生平安","服務器在國外,慢"]} }av_catalog["大陸"]["1024"][1] += ",可以用爬蟲爬下來" print(av_catalog["大陸"]["1024"]) #ouput ['全部免費,真好,好人一生平安', '服務器在國外,慢,可以用爬蟲爬下來']
其它姿勢


#values >>> info.values() dict_values(['LongZe Luola', 'XiaoZe Maliya'])#keys >>> info.keys() dict_keys(['stu1102', 'stu1103'])#setdefault >>> info.setdefault("stu1106","Alex") 'Alex' >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} >>> info.setdefault("stu1102","龍澤蘿拉") 'LongZe Luola' >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}#update >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} >>> b = {1:2,3:4, "stu1102":"龍澤蘿拉"} >>> info.update(b) >>> info {'stu1102': '龍澤蘿拉', 1: 2, 3: 4, 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}#items info.items() dict_items([('stu1102', '龍澤蘿拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')])#通過一個列表生成默認dict,有個沒辦法解釋的坑,少用吧這個 >>> dict.fromkeys([1,2,3],'testd') {1: 'testd', 2: 'testd', 3: 'testd'}
循環dict?


#方法1 for key in info:print(key,info[key])#方法2 for k,v in info.items(): #會先把dict轉成list,數據里大時莫用print(k,v)
程序練習
程序: 三級菜單
要求:?
- 打印省、市、縣三級菜單
- 可返回上一級
- 可隨時退出程序


menu = {'北京':{'海淀':{'五道口':{'soho':{},'網易':{},'google':{}},'中關村':{'愛奇藝':{},'汽車之家':{},'youku':{},},'上地':{'百度':{},},},'昌平':{'沙河':{'老男孩':{},'北航':{},},'天通苑':{},'回龍觀':{},},'朝陽':{},'東城':{},},'上海':{'閔行':{"人民廣場":{'炸雞店':{}}},'閘北':{'火車戰':{'攜程':{}}},'浦東':{},},'山東':{}, }exit_flag = False current_layer = menulayers = [menu]while not exit_flag:for k in current_layer:print(k)choice = input(">>:").strip()if choice == "b":current_layer = layers[-1]#print("change to laster", current_layer) layers.pop()elif choice not in current_layer:continueelse:layers.append(current_layer)current_layer = current_layer[choice]
4.集合操作
集合是一個無序的,不重復的數據組合,它的主要作用如下:
- 去重,把一個列表變成集合,就自動去重了
- 關系測試,測試兩組數據之前的交集、差集、并集等關系
常用操作


s = set([3,5,9,10]) #創建一個數值集合 t = set("Hello") #創建一個唯一字符的集合 a = t | s # t 和 s的并集 b = t & s # t 和 s的交集 c = t – s # 求差集(項在t中,但不在s中) d = t ^ s # 對稱差集(項在t或s中,但不會同時出現在二者中) 基本操作: t.add('x') # 添加一項 s.update([10,37,42]) # 在s中添加多項 使用remove()可以刪除一項: t.remove('H') len(s) set 的長度 x in s 測試 x 是否是 s 的成員 x not in s 測試 x 是否不是 s 的成員 s.issubset(t) s <= t 測試是否 s 中的每一個元素都在 t 中 s.issuperset(t) s >= t 測試是否 t 中的每一個元素都在 s 中 s.union(t) s | t 返回一個新的 set 包含 s 和 t 中的每一個元素 s.intersection(t) s & t 返回一個新的 set 包含 s 和 t 中的公共元素 s.difference(t) s - t 返回一個新的 set 包含 s 中有但是 t 中沒有的元素 s.symmetric_difference(t) s ^ t 返回一個新的 set 包含 s 和 t 中不重復的元素 s.copy() 返回 set “s”的一個淺復制


>>> a = {1,2,3,4} >>> b ={3,4,5,6} >>> a {1, 2, 3, 4} >>> type(a) <class 'set'> >>> a.symmetric_difference(b) {1, 2, 5, 6} >>> b.symmetric_difference(a) {1, 2, 5, 6} >>> >>> >>> a.difference(b) {1, 2} >>> a.union(b) {1, 2, 3, 4, 5, 6} >>> a.issu a.issubset( a.issuperset( >>> a.issubset(b) False
?