# Python複習講義_part2 ## 資料容器 list、tuple、dict、set ## 簡單整理 ```csvpreview {header="true"} 物件,變動性,順序性,唯一性 str,不可變,有,無 list,可變,有,無 tuple,不可變,有,無 dict,可變,無,有(keys) set,不可變,無,有 ``` ## 字串 ![](https://i.imgur.com/pRdJTyu.png) 如上圖,字串是由一格一格的字元串接而成的,而那一格一格串接的結構即為串列。因此字串是由字元放入串列中而成。 ```a=Hello```即可看成有五個格子,而為了取資料方便,每個格子也有它各自的編號。 **範例** ```python= a="Hello" print(a[0]) print(a[1]) print(a[2]) print(a[3]) print(a[4]) ``` 輸出 ``` H e l l o ``` 由上可知,串列起始編號為0,最末編號為'n-1',n為格子數(長度)。 >* len()函數可以取得串列的長度 範例 ```python= a = "Hello" b = "non _ zero" print(len(a)) print(len(b)) ``` >輸出 ``` 5 10 ``` ![](https://i.imgur.com/jQbj2Q9.png) :::warning :warning: 5 跟 10 是字串 a b 的長度,但a跟b的編號分別是(0 ~ 4)跟(0 ~ 10),要注意到 b ,空格也佔一格的大小,也算在字串裡面。 另外,len(a)回傳的5的資料型態為int。 ::: ### 字串方法介紹: 串列的切片、常見的字串操作、搜尋 #### 串列的切片: 1. 一般方法 ```python= a = "Hello" print(a[0]+a[1]+a[2]) #字串與字串之間可直接相加 b = "afsdgdftysrthfhdfgj"#太長的字串可用迴圈做 for i in range(3,10): print(b[i],end='') ``` > 輸出 ``` Hel dgdftys ``` ![](https://i.imgur.com/SY8sAof.png) 2. 特殊切字串方法,與上述的迴圈中range概念很像 ``` 語法: a[起點:終點:跳階] 起點預設是0,終點預設為字串 的長度(len(a)),跳接預設為1,一格一格前進。 ``` :warning: 跳階可為負的! ```python= b = "afsdgdftysrthfhdfgj" print(b[0]) # 印第0格 print(b[3:10]) # 印第(3~9)格 print(b[:]) #印全部 print(b[:-1]) #從頭印到最後倒數第一個 print(b[:-2]) #從頭印到最後倒數第二個 print(b[1::2])#從第一格開始到最後一格,每次跳兩格 print(b[-1::-1])#從最後一格開始,每次跳往前跳一格(倒者印) ``` >輸出 ``` a dgdftys afsdgdftysrthfhdfgj afsdgdftysrthfhdfg afsdgdftysrthfhdf fddtstfdg jgfdhfhtrsytfdgdsfa ``` ![](https://i.imgur.com/G33mv70.png) ### 字串操作 :::danger :fire: 字串是所謂immutable也就是無法修改,你可以透過,宣告新的記憶體區段(變數)來做到字串的修改 字串修改範例 ``` a = "123456789" a[3] = "a" ``` 會得到這個錯誤 ![](https://i.imgur.com/LYrk8DU.png) 我們必須這樣 ``` a = "123456789" b = a[0:3] + "a" +a[4:] print(b) ``` 輸出 ``` 123a56789 ``` ![](https://i.imgur.com/Pbm13BM.png) ::: python 本身就內建很多字串的操作函數,我們來看幾個比較重要的吧。 以下是常見的字串操作 #### 1. 字元轉換 >大小寫 ```python= str.upper() #直接返回一個新的str大寫字串 str.lower() #直接返回一個新的str小寫字串 str.swapcase() #大小寫互換 ``` >字首 ```python= str.capitalize() #將首字母變大寫 ,其餘的變成小寫 str.title() #將字串 中的每個單詞的首字母變成大寫,其餘變小寫 ``` >範例 ```python= _str = "aPPle" #直接返回一個新的str大寫字串 print(_str.upper()) #直接返回一個新的str小寫字串 print(_str.lower()) #大小寫互換 print(_str.swapcase()) #將首字母變大寫 ,其餘的變成小寫 print(_str.capitalize()) #將字串 中的每個單詞的首字母變成大寫,其餘變小寫 print(_str.title()) print(_str) ``` >輸出 ``` APPLE apple AppLE Apple Apple aPPle ``` ![](https://i.imgur.com/rd8dQ6P.png) #### 2. 頭尾刪除 **strip ()** >功能 返回所有字符從開始及字符串的末尾(默認空格字符)被去除後的字符串 >語法 ``` python str.strip(chars) ``` 參數 * chars 為指定字元 >範例 ```python= str = "0000this is string example....wow!!!00000" print(str.strip('0')) ``` 當執行程式會變成 this is string example....wow!!! #### 3. 搜尋 **count** >功能 計算特定字串出現次數 >語法 ``` python str.count(string,start,end) ``` 參數 * string 為 str 的子字串 * start 為尋找字串的起點 * end 為尋找字串的終點 "回傳值為int" >例子 ```python= str = "0000this is string example....wow!!!00000" print(str.count("0")) ``` 當執行程式會變成 9 ![](https://i.imgur.com/vC7CvpV.png) **index() 或 find() 找尋位置** 在字串後加上 .index(要找的子字串) 或 .find(要找的子字串) ,當子字串找的到時,兩個方法的回傳值的是字串首個字母的位置。 語法格式: ``` str.index(substring) str.find(substring) ``` 範例程式: ```python= lesson ='the new skill I am learning this year : Python.' print(lesson.index('the')) print(lesson.find('the')) print(lesson.index('I')) print(lesson.find('I')) ``` 輸出: ``` 0 0 14 14 ``` ![](https://i.imgur.com/eNee9lH.png) 預設的找尋的方向是由左至右,如果想從右邊開始找可以在 find() 與 index() 前面加上 r,變成rfind()、rindex(),就可以從右邊開始找。 以找尋 e 這個字母為例,會得到不一樣的位置回覆。 範例程式: ```python= lesson ='the new skill I am learning this year : Python.' print(lesson.find('e')) print(lesson.rfind('e')) print(lesson.index('e')) print(lesson.rindex('e')) ``` 輸出: ``` 2 34 2 34 ``` ![](https://i.imgur.com/Y0mwZ0j.png) 當找不到目標時呢?index() 方法會回覆 ValueError,find() 則回傳 -1。 ```python= #使用find(): lesson ='the new skill I am learning this year : Python.' print(lesson.find('peace')) #輸出-1 #使用index(): print(lesson.index('peace')) # Traceback (most recent call last): #ValueError: substring not found ``` ![](https://i.imgur.com/PKOh2v6.png) **replace()** 原本的字串值並不會改變,只是加上replace()方法後,回傳一個修改後的字串,原本的字串不會改變。 語法 replace(要被替換的值, 替換成這個值) 程式 ```python= lesson ='the new skill I am learning this year : Python.' print(lesson.replace('Python', 'playing guitar')) #the new skill I am learning this year : playing guitar. print(lesson) #the new skill I am learning this year : Python. ``` --- ## 串列 定義: ``` 串列:由零或多個元素組成的,以「,」逗號分隔,並且放在[]裡面。 語法:[element1,element2.....] ``` 建立基本的串列結構 ``` List1 = [] List2= [1,2,3,4] List3 = [1,"a",4,": , ; ", "c",[1,2,3]] print(List1,List2,List3,sep=" ") ``` 程式示範: ```python= a_list = [1,2,'a',3.1412] complicated_list = [1,[2,'kk',3],89.23,'mk'] print(a_list) print(complicated_list) ``` 輸出 ``` [1, 2, 'a', 3.1412] [1, [2, 'kk', 3], 89.23, 'mk'] ``` ![](https://i.imgur.com/v5S2EZl.png) :::info :accept: List沒有規定你只能存特定資料,所以不管數字、字串、甚至在一個list都可以儲存 ::: >list()函數 會把資料型態全都轉型成list的型態,我們試者把`range()`跟`string`轉型成list ```python= print(list(range(10))) a = "ABCDEF" lis = list(a) print(a) print(type(a)) print(lis) print(type(lis)) ``` 輸出 ``` [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ABCDEF <class 'str'> ['A', 'B', 'C', 'D', 'E', 'F'] <class 'list'> ``` ![](https://i.imgur.com/X5f0AvF.png) ### list 基本操作 list 的基本操作幾乎跟字串一模一樣,但不同的是,list是可變動的,而string是不可改變的 ```python= b = [1,2,3,4] print(b) b[0] = [1,2,3] print(b) a = "abj" print(a) a[0] = "k" # 不合法 print(a) ``` >輸出 ``` [1,2,3,4] [[1,2,3],2,3,4] abj ``` :warning: a[k] #不合法 ![](https://i.imgur.com/NKzw3y3.png) --- 還有幾個跟string很像的用法 #### 1. 長度和取值 list = [1,2,3,4,5] len(list) #會等於5 `len(list)` 會回傳最外層的格子數,而不是裡面裝了多少東西,所以 list = [[],[1,25,6],[[1,2,3],4],[1,2,3]] len(list) #會等於4 但如果我們把他拆開細看會發現 ```python= list = [[], [1, 25, 6], [[1, 2, 3], 4], [1, 2, 3]] print("list = ",list) print("長度", len(list)) for i in range(0,len(list)): print("第",i,"格",list[i],"長度",len(list[i])) ``` 用迴圈跑完上面的結果可以發現 ``` list = [[], [1, 25, 6], [[1, 2, 3], 4], [1, 2, 3]] 長度 4 第 0 格 [] 長度 0 第 1 格 [1, 25, 6] 長度 3 第 2 格 [[1, 2, 3], 4] 長度 2 第 3 格 [1, 2, 3] 長度 3 ``` ![](https://i.imgur.com/5UIznb9.png) 如果我們想用25我們就要取第1格的第1格 list[1][1] #這是25 list[2][0][2] 猜猜這是多少 這就是多維陣列的概念,有了這種無限擴充性能,list可以幫助我們在python上做出很多事情。 ![](https://i.imgur.com/YBhy6lF.png) #### 2. 切片取值 複習一下切片取值 用法 : a[start:end:step] a[start:end] #取得start~end-1的元素 a[:end] #取得到end-1的元素 a[:-n] #取得所有元素不含最後n個 a[-n:] #取得串列後n名 a[start:] #取得從start開始的所有元素 a[start:end] #取得所有元素 a[start:end:step] ##取得start~end-1的元素每step跳一個 程式範例,有一個資料是全班10個人的成績(由大到小) ```python= score = [93, 87, 80, 73, 62, 61, 60, 49, 23, 0] print("班上前五名", score[0:5]) print("倒數三名", score[-3:]) print("成績由小排到大", score[-1::-1]) ``` 輸出 ``` 班上前五名 [93, 87, 80, 73, 62] 倒數三名 [49, 23, 0] 成績由小排到大 [0, 23, 49, 60, 61, 62, 73, 80, 87, 93] ``` ![](https://i.imgur.com/Lom73e2.png) #### 2. 運算 list 也同樣有`+`跟`*`的運算 list1 + list2 #兩個list合併 list1 * n #複製list1 n 遍 >程式範例 ```python= class1 = [61, 60, 49, 23, 0] class2 = [34, 56, 78, 90, 87] class3 = class1 + class2 print(class3) print(class2*2) ``` >輸出 ``` [61, 60, 49, 23, 0, 34, 56, 78, 90, 87] [34, 56, 78, 90, 87, 34, 56, 78, 90, 87] ``` ![](https://i.imgur.com/LrU2llZ.png) #### 3. 刪除 當你要刪除一個陣列裡的元素,你要寫 del lis[i] #刪除串列中的某個元素 del lis[start:end:step] #刪除片段 del lis #刪除整個串列 ### List 方法 #### 1. 增/減 list >list.append() 把東西附加到 list的最後面(會保持原來的資料型態) 語法: ``` list.append(data) ``` >程式範例 ```python= a = "wwww" b = 1231232 list_1 = [1, 2, 3, 4] list_2 = [1, 0] print(list_1) list_1.append(list_2) print(list_1) list_1.append(a) print(list_1) list_1.append(b) print(list_1) ``` 輸出 ``` [1, 2, 3, 4] [1, 2, 3, 4, [1, 0]] [1, 2, 3, 4, [1, 0], 'wwww'] [1, 2, 3, 4, [1, 0], 'wwww', 1231232] ``` >list.extend() ``` list.extend(data) ``` 同樣會把東西附加到 list的最後面,但只會丟元素進去,不會丟容器(list就是一種容器) >程式範例 ```python= list_1 = [1, 2, 3, 4] list_2 = [1, 0] a = "awwww" print(list_1) list_1.extend(list_2) print(list_1) list_1.extend(a) print(list_1) ``` 輸出 ``` [1, 2, 3, 4] [1, 2, 3, 4, 1, 0] [1, 2, 3, 4, 1, 0, 'a', 'w', 'w', 'w', 'w'] ``` ![](https://i.imgur.com/Zg4nzgC.png) >list.insert(index,obj) 輸入 ```python= list_1 = [1, 2, 3, 4, [1,2]] list_2 = [3,5] a = "wowow" print(list_1) print(list_1[3]) list_1.insert(3, list_2) print(list_1) print(list_1[3]) list_1.insert(3,a) print(list_1) print(list_1[3]) ``` >輸出 ![](https://i.imgur.com/9RKFCG7.png) >list.pop(index) 回傳list[index],並且刪除他,預設的index會是最後一個 >程式範例 ```python= lis = [1,2,3,4,5,6] print(lis.pop()) print(lis) print(lis.pop()) print(lis) print(lis.pop()) print(lis) ``` 輸出 ``` 6 [1, 2, 3, 4, 5] 5 [1, 2, 3, 4] 4 [1, 2, 3] ``` ![](https://i.imgur.com/aUjBDo0.png) 對他pop三次,依序丟掉最後一個數字 >list.remove(想刪除的東西) 當你不知道你想要刪除的東西在哪邊,就使用 remove()方法來移除指定的元素,不過只能刪除一次,但可以搭配迴圈把他全部刪除。 語法格式: list.remove(元素) >程式範例 ```python= lis = [1,2,3,4,5,5,5,5,7,1,1,0] while 1 in lis: lis.remove(1) print(lis) ``` 輸出 ``` [2, 3, 4, 5, 5, 5, 5, 7, 0] ``` ![](https://i.imgur.com/mGq6yTw.png) #### 2.排序 >list.sort() 將list按照大小排序 語法 list.sort([key],[reverse]) 參數 * key:分類依據(為一函式,list中的每項會被當成參數傳入此函式中) * reverse:是否由大到小排序(默認為False) >實際範例 ```python= list_1=[1,3,2,4] list_1.sort() print(list_1) ## list_1=[1,2,3,4] list_1.sort(reverse=True) print(list_1) ## list_1=[4,3,2,1] list_2=['a','b','C','D'] list_2.sort() print(list_2) ##list_2['C','D','a',b'] 依照ASCII code list_2.sort(key=str.upper) ##使用upper後的內容排序 print(list_2) ##list_2=['a','b','C','D'] ``` >輸出 ``` [1,2,3,4] [4,3,2,1] ['C','D','a',b'] ['a','b','C','D'] ``` ![](https://i.imgur.com/qiV5rtu.png) ```python= scores = [ ('Jane', 'B', 12), ('John', 'A', 15), ('Dave', 'B', 11)] # 依照第三個數字元素排序 scores.sort(key = lambda s: s[2]) print(scores) ``` >輸出 ``` [('Dave', 'B', 11), ('Jane', 'B', 12), ('John', 'A', 15)] ``` ![](https://i.imgur.com/UgFyToA.png) :::info :information_source: 另有一個方法為sorted,跟sort不一樣的地方為sorted會再排序後,產生一個新的list,不會改變原本的list。 ::: #### 3.字串⇋list * >split(分割條件) 可以給定分割條件將string切分成好幾段需要的段落,返回一個list 語法 ```python 目標字串.split(str,num) ``` 參數 * str = 這是任何分隔符,空白的情況下是空格 * num = 要分割的行數 >例子 ``` python= str = 'Quan 24 45 57 79' print (str.split()) print (str.split(' ',1)) print (str.split(' ',2)) print (str.split('4',2)) ``` 注意到他會把要斷點的地方吃掉(輸出如下) ['Quan', '24', '45', '57', '79'] ['Quan', '24 45 57 79'] ['Quan', '24', '45 57 79'] ['Quan 2', ' ', '5 57 79'] ![](https://i.imgur.com/KZQh3Wn.png) * > join(合併) 把list中的東西組合起來,變成一個字串 >語法 ```python= str.join(sequence) ``` 參數 * str = 連接符號(一個string) * sequence = 連接順序 (一個list) >例子 ``` python= str1 = '' list = ['A','B','C','D','E'] new1_str = str1.join(list) print(new1_str) str2 = '--' # 以 -- 合併 new2_str = str2.join(list[::-1]) # 反向合併 print(new2_str) ``` 輸出如下 ```python ABCDE # new1_str E--D--C--B--A # new2_str ``` ![](https://i.imgur.com/LIlCC5x.png) ### 迭代 #### in 和 not in in 跟 not in 是之前談過的 `關係運算子`,並會用在物件跟物件的比較 a in b 如果是true 代表 a 這個元素 在 b 裡面 a not in b 如果是true 代表 a 這個元素 不在 b 裡面 通常 a 是某個元素 (字元、數字) b 是某個容器 (string,list) >例子 ``` python= list= ['apple','c++','python','good'] print('bed' in list) print('Hi' not in list) word = "Hello welcome to my class" print('q' in word) print('H' not in word) ``` 輸出如下 ```python False True False False ``` 實際操做一下,現在有個購買清單,我媽媽會一直輸入清單,如果不在清單上面,就把他加入清單,想怎麼做會比較好 ```python= shopping_list = [] while True: n = input() if n == "-1": break elif n not in shopping_list: shopping_list.append(n) print(shopping_list) ``` 輸出 ``` the new skill I am learning this year : playing guitar. the new skill I am learning this year : Python. ``` ## tuple(元組)--無法更動的序列 >Tuple資料組有以下特點 1. Tuple資料組建立之後,裏頭的資料就不可以再改變。 2. Tuple資料組中的資料可以有不同的資料型態,甚至可以包含另一個資料組。 3. Tuple資料組可以利用指定運算子把資料分配給多個變數。 4. Tuple資料組顯示的時候,會用圓括弧( )把資料括起來。 簡單來說tuple就是不可變動的list,專門用在,一些不可變動的資料儲存,例如客戶訊息、遊戲參數,在操作上基本都跟list很像,下面有幾個例子 ### 基本操作 #### 1.創建 tuple 創建方式 tup = (元素1,元素2,元素3,元素4......) 跟list一樣存在一格一格的格子裡面,一樣可以通過格子去做存取 >範例程式 ```python= tup = (1,2,3,4,5) print(type(tup)) print(tup) print(tup[2]) print(tup[3]) ``` >範例輸出 ``` <class 'tuple'> (1, 2, 3, 4, 5) 3 4 ``` ![](https://i.imgur.com/pAhGtCy.png) #### 2.tuple 修改,錯誤示範 tuple 跟 list最大的差別就是,無法修改元素 >範例程式 ```python= tup = (1,2,3,4,5) tup[0] = 5 ``` >範例輸出 ``` Traceback (most recent call last): File "/Users/apple/Desktop/Learning/test.py", line 2, in <module> tup[0] = 5 TypeError: 'tuple' object does not support item assignment ``` ![](https://i.imgur.com/pFrNgkD.png) ![](https://i.imgur.com/1R0B6un.png) 直接報錯誤 --- **如果真的想要修改tuple內容值,可以用下列方式** 1. **重新賦值** >範例程式 ```python= tup = (1,2,3,4,5) print(tup) tup = (5,2,3,4,5) print(tup) ``` >範例輸出 ``` (1, 2, 3, 4, 5) (5, 2, 3, 4, 5) ``` ![](https://i.imgur.com/zpOnIeq.png) 2. **將tuple轉型成list,利用list更改內容,再轉型回tuple** tuple 跟 list 之間也可以透過轉型進行互換利用透過 `tuple()`跟`list()`,來作轉換 >範例程式 ```python= tup = (1,2,3,4,5) print(tup) lis = list(tup) lis.append(7) print(lis) tup = tuple(lis) print(tup) ``` >範例輸出 ``` (1, 2, 3, 4, 5) [1, 2, 3, 4, 5, 7] (1, 2, 3, 4, 5, 7) ``` #### 3.3.tuple 迭代 tuple 也是可迭代物件,可以使用切片功能,也可以用for迭代 >範例程式 ```python= tup = (1,2,3,4,5) for i in tup: print(i,end = " ") print() for i in tup[-1::-1]: print(i, end=" ") print() ``` >範例輸出 ``` 1 2 3 4 5 5 4 3 2 1 ``` ![](https://i.imgur.com/ZKOx1Ja.png) ## Dist(字典) -- key-map 在 Python 的字典中,每一個元素都由鍵 (key) 和值 (value) 構成,結構為key: value 。不同的元素之間會以逗號分隔,並且以大括號 {}圍住。 字典提供了非常快的查詢速度,使用的方法如下: d = {key1: value1, key2: value2} 什麼時候會使用到 dictionary 呢 ? dictionary 是一種較為複雜的資料結構,對於資料的查找很方便。 假如說我們要做一個人的身體數據資料表,我們可以這要 ```python= people1 = { '身高':180, '體重':78, '性別':'男性', '大學':'中央大學' } ``` 這樣就完成對一個人的資料儲存,所以當我今天想知到他的身高我可以說 print(people1['身高']) 就可以得到 180 如果我今天有好幾個人 ```python= people1 = { '身高':180, '體重':78, '性別':'男性', '大學':'中央大學' } people2 = { '身高':170, '體重': 44, '性別':'女性', '大學':'台灣大學' } people3 = { '身高':165, '體重':40, '性別':'女性', '大學':'政治大學' } ``` 我就可以清楚的知道每個人的詳細資料存在哪裏 :::info dict 中 key 必須是唯一且不可變的,也就是在寫程式時不可隨意更動,如整數、字串、tuple 等。 value 可以是任何的資料型態,例如: 字串、整數、list、物件、字典等等。 ::: 所以我今天在用一個dict把這些人包起來,並用人名當key ```python= People_dict = { '張小明':people1, '林小山':people2, '吳淑鳳':people3 } ``` 試者呼叫一下,張小明的資訊 ```python= print(People_dict['張小明']) ``` 輸出 ``` {'身高': 180, '體重': 78, '性別': '男性', '大學': '中央大學'} ``` 這就是字典在資料儲存的方便性 #### 基本操作 dict 常見方法 > len() > 回傳字典鍵數的數目 範例程式 ```python= people = { '姓名' : '王小明', '生日' : '2020/07/15', '性別' : '男性', '大學' : '中央大學', '系別' : '資訊工程學系' } print(len(people)) ``` 範例輸出 ```python= 5 ``` ![](https://i.imgur.com/8ayERpY.png) > dict.items() > 回傳所有 (keys,value) 的 tuple List 範例程式 ```python= for items in people.items(): print(items) ``` 範例輸出 ```python ('姓名', '王小明') ('生日', '2020/07/15') ('性別', '男性') ('大學', '中央大學') ('系別', '資訊工程學系') ``` ![](https://i.imgur.com/cOeLaZB.png) > dict.keys() > 回傳所有 (keys) 的list > 範例程式 ```python= for key in people.keys(): print(key) ``` 範例輸出 ```python 姓名 生日 性別 大學 系別 ``` ![](https://i.imgur.com/WVje0Rv.png) > dict.values() > 回傳所有 (value) 的 List 範例程式 ```python= for value in people.values(): print(value) ``` 範例輸出 ```python 王小明 2020/07/15 男性 中央大學 資訊工程學系 ``` ![](https://i.imgur.com/U0aBTJS.png) > dict.update() > 大範圍更新字典 :::info python 版本更新後可以用 {**b,**c } 來進行字典的合併 ::: 範例程式 ```python= info = { '興趣' : ['彈吉他','寫code','唱歌'], '身高' : 200, '體重' : 53, } people.update(info) for key,value in people.items(): print(f"{key} : {value}") ``` 範例輸出 ```python 8 姓名 : 王小明 生日 : 2020/07/15 性別 : 男性 大學 : 中央大學 系別 : 資訊工程學系 興趣 : ['彈吉他', '寫code', '唱歌'] 身高 : 200 體重 : 53 ``` ![](https://i.imgur.com/wP6Eq0K.png) > pop() > 刪除字典特定元素,同時回傳被刪除的元素 語法 dict.pop(key,[,defult]) # key 搜尋要刪除的鍵 # defult 如果沒有找到就回傳 defult (不寫會報error) 範例程式 ```python= print(people.pop('性別')) print(people) ``` 範例輸出 ```python 男性 {'姓名': '王小明', '生日': '2020/07/15', '大學': '中央大學', '系別': '資訊工程學系', '興趣': ['彈吉他', '寫code', '唱歌'], '身高': 200, '體重': 53} ``` ![](https://i.imgur.com/5nW3tQU.png) > popitem() , clear() , del * dict.popitem() 隨機刪除字典特定元素,同時回傳被刪除的(key,value) * dict.clear() 刪除所有元素 * del dict 刪除整個字典 語法 dict.pop(key,[,defult]) # key 搜尋要刪除的鍵 # defult 如果沒有找到就回傳 defult (不寫會報error) 範例程式 ```python= print(people.popitem()) print(people) del people['大學'] print(people) people.clear() print(people) ``` 範例輸出 ```python ('體重', 53) {'姓名': '王小明', '生日': '2020/07/15', '大學': '中央大學', '系別': '資訊工程學系', '興趣': ['彈吉他', '寫code', '唱歌'], '身高': 200} {'姓名': '王小明', '生日': '2020/07/15', '系別': '資訊工程學系', '興趣': ['彈吉他', '寫code', '唱歌'], '身高': 200} {} ``` ![](https://i.imgur.com/h6vpilK.png) ## set(集合)--數學的集合範疇 集合的基本觀念就是, **無序** 且 **唯一** 、 **不可變動** , 裡面許多性質都跟數學的集合性質重疊 ### set建立 >建立集合 使用 {} 範例程式 ```python= a = {1,2,3,4,5} #集合建立 print(a) b = {1,1,1,1,3,4,5} #元素唯一性 print(b) ``` 範例輸出 ```python {1, 2, 3, 4, 5} {1, 3, 4, 5} ``` ![](https://i.imgur.com/aaYzyVR.png) >使用set集合轉型 > 可以使用set() 將指定的 list dict set tuple 建立成集合 > len() 回傳集合的基數 ```python= word = "Apple Pencil" print(set(word)) list = ['a','a','b','c','h'',k'] print(set(list)) tup = ('a','a','b','c','h'',k') print(set(tup)) w_ord = set(word) l_ist = set(list) t_up = set(tup) print(len(w_ord)) print(len(l_ist)) print(len(t_up)) ``` 範例輸出 ```python {'l', 'c', 'e', 'P', 'i', 'n', 'p', ' ', 'A'} {'c', 'h,k', 'a', 'b'} {'c', 'h,k', 'a', 'b'} 9 4 4 ``` ![](https://i.imgur.com/MdKjKBR.png) ### set使用時機 集合通常用在大數據分析通過集合跟串列的轉換,可以快速的把相同、重複的元素剔除掉,減少記憶體浪費和增加效率 範例: 分析質因數分解,利用set快速把因數把,質因數挑出來 ```python= n = 1536 div = 2 num = [] while n > 1: if n % div == 0 : n //= div num.append(div) else: div += 1 print(num) num = list(set(num)) print(num) ``` 範例輸出 ```python [2, 2, 2, 2, 2, 2, 2, 2, 2, 3] [2, 3] ``` ![](https://i.imgur.com/02F6tIx.png) ### 集合操作 ```csvpreview {header="true"} 符號,說明,函數 &,交集,intersection() |,聯集,union() -,差集,difference() ^,動稱差集,symmetric_difference() ==,等於, !=,不等於, in,是成員, not in,不是成員, ``` 範例: ```python= A = {1,2,3,4,5} B = {4,5,6,7,8} print("A交集B",A & B) print("A聯集B",A | B) print("A差集B",A - B) print("A動稱差集B",A ^ B) C = {1,2,3,4,5} D = {1,2,3} E = {4} print(A == B) print(A == C) print(A!=B) print(E in A) print(D in A) ``` 範例輸出 ``` A交集B {4,5} A聯集B {1,2,3,4,5,6,7,8} A差集B {1,2,3} A動稱差集B {1,2,3,6,7,8} False True True False False ``` ![](https://i.imgur.com/KhrR0aR.png) ## import >**語法** ```python= import name ``` ### 範例 #### 1.math ``` python= import math a = math.pi print(a) ``` > 輸出 ``` a=3.141592653589793 ``` ``` python= import math as m a=m.pi print(a) ``` >輸出同上 ``` python= a= math.pi #沒有import math,因此找不到math.pi print(a) ``` >輸出錯誤 #### 2.random ```python= import random min = 1 max = 10 for i in range(5): ret = random.randint(min, max) print(ret) ``` >輸出 ``` 4 9 3 1 9 ``` ![](https://i.imgur.com/xDNqz1C.png) * 每次輸出都可能不同。 #### 3.pygame ``` python= import pygame pygame.init() ```