###### tags: `programming` **PYTHON筆記** === >Beautiful is better than ugly. >Simple is better than compex. >Readability counts. # 程式結構 ## 變數 不用特別指定型態。 ### 變數命名及宣告 ```python= '''Example''' x = 100 y = 200 z = 100; w = 200 #用';'分隔敘述句 p = q = 100 name, eng, math, phy = 'Nick', 92, 88, 32 #用','隔開一起宣告 a = int() #還不想給值的宣告 ``` 其他:[條件性變數指定](#條件性變數指定) ### 弱型別語言 可以隨意修改變數型態 ### 命名規則 1. 不可以用數字開頭 2. 不可使用特殊字元 3. 大小寫不同 4. 不可使用保留字 |保留字參考||||| | :--------: | :--------: | :--------: |:--------: |:--------: | | False | class | finally | is | return | | None | continue | for | lambda | try | | True | def | from | nonlocal | while | | and | del | g;obal | not | with | | as | elif | if | or | yield | | assert | else | import | pass | break | | recept | in | raise | sum | max | 5. 用有意義的命名 ## 變數型態 * int:整數 ```python= '''Example''' a = 10 i = 1 j = 2 print(i+j) #3 ``` * float:浮點數 ```python= '''Example''' b = 3.14159 ``` * str:字串 ```python= '''Example''' c = "Nick" d = 'Nick' e = '''Hello, world.''' i = '1' j = '2' print(i+j) #12 ``` * boolean:布林值 * 在判斷裡的布林值:[傳送門](#判斷布林值) ```python= '''Example''' f = False g = True ``` * None ### 回傳變數型態 #### ==type(a)== 回傳a的變數型態 ```python= '''Example''' print(type(True)) # <class 'bool'> print(type(int(a))) # <class 'int'> ``` #### ==isinstance(a,type)== 實體,回傳a是不是type的實體 ```python= '''Example''' type(grade) == int isinstance(grade, float) #False:變數grade是否為浮點數的結果 ``` ### 變數型態轉換 * int(x) * str(x) ## 運算 ex:10 + 20 其中10和20是operand運算元,'+'是operator運算子 ### 算術運算 | Operator | + | - | * | / | // | % | ** | |:--------:|:--------:|:--------:|:--------:|:--------:|:--------:|:--------:|:--------:| |Meaning|加法|減法|乘法|除法|整除|取餘數|次方| |Example|11+2|11-2|11*2|11/2|11//2|11%2|11**2| |Result|13|9|22|5.5|5|1|121| ### 算術運算相關函式 #### ==round(variable, num)== 四捨五入 ```python= '''Example''' print(round(3.14159, 2)) #3.15 ``` #### ==math.ceil(variable)== 無條件進位 ```python= '''Example''' import math print(math.ceil(3.14159)) #4 ``` #### ==math.floor(variable)== 無條件捨去 ```python= '''Example''' import math print(math.floor(3.14159)) #3 ``` #### ==math.sqrt(variable)== 開根號 ```python= '''Example''' import math print(math.sqrt(16)) #4 ``` ### 字串運算 | Operator | + | * | [] | [:] | in | % | |:--------:|:--------:|:--------:|:--------:|:--------:|:--------:| :--------: | | Meaning | 相連 | 重複 | 取值 | 切片 | 是否在 | 格式化插入 | | Example |'ab'+'cd'|'a'*3|'abc'[1]|'abcd'[1:3]|'a' in "apple"|'%d'%10| |Result|'abcd'|'aaa'|'b'|'bc'|True|'10'| * 格式化插入詳細說明:[傳送門](#print()) ```python= '''Example''' Hello = "Hello,World" - "," - "World" #ERROR hello = "Hello,World" hello.upper() #HELLO,WORLD hello.lower() #hello,world hello.replace('Hello','Hi') #Hi,World ``` #### 字串切片==str[a:b]== 字串切片從a到b-1 ex: | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | H | e | l | l | o | , | N | i | c | k | ```python= '''Example''' a = 'Luminescence' print(a[1]) #'u' print(a[3:6]) #'ine' print(a[0:5]) #'Lumin' print(a[6:]) #'scence' print(a[-1]) #'e' ``` ### 關係運算 | Operator | == | != | > | < | >= | <= | is | |:--------:|:--------:|:--------:|:--------:|:--------:|:--------:|:--------:| :--------: | |Meaning|等於|不等於|大於|小於|大於等於|小於等於|參考是否相同| |Example|11==2|11!=2|11>2|11<2|11>=2|11<=2|-| |Result|False|True|True|False|True|False|-| * is檢查reference是否相同:[傳送門](#list_1-is-list_2) * python可以寫 ` 2 < x <= 7 `,C絕對不可以。 ### 邏輯運算 | Operator | and| or | not | |:--------:|:--------:|:--------:|:--------:| |Meaning|且|或|非| |Example|True and False|True or False|not True| |Result|False|True|False| ## ==input()== #### input():回傳使用者輸入的字 input([prompt]) | | 說明 | | :------: | :------: | | prompt | 提示字 | | [ ] | 表示可以省略 | ```python= '''Example''' name = input('What is your name?') ``` ```python= '''Example''' """input會回傳str型態""" age = input('Your age?') print(type(age)) #<class 'str'> Age = int(input('Your age?')) #經由int轉換型態 print(type(Age)) #<class 'int'> AGE = eval(input('Your age?')) #eval()會依據輸入的內容進行轉換 print(type(AGE)) ``` ```python= '''Example''' """同時輸入多個""" a, b, c = map(float, input('please input number?').split(',')) #map:集中處理 #float:轉換型態 #.splt(','):分割,以','為基準 ``` ## ==print()== #### print():輸出 print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) | | 說明 | 預設值 | | :------: | :------: | :------: | | objects | 參數 | - | | sep | 每個object之間的間隔 | ' ' | | end | 結尾 | '\n' | ```python= '''Example''' name = 'Nick'; age = 28 print(name) #'Nick' print(age) #28 print("fly", "Phoenix", "fly") #fly Phoenix fly print("fly", "Phoenix", "fly", sep = '_') #fly_Phoenix_fly print("fly", "Phoenix", "fly", end = '~\n') #fly Phoenix fly~ """字串與變數混合""" print("Your name is", name, ", and your age is", age) #Your name is Nick , and your age is 28 print("Your name %s, and your age %d." %(name, age)) #Your name is Nick, and your age is 28. print("Your name {}, and your age {}." .format(name, age)) #Your name is Nick, and your age is 28. string = "Your name {}, and your age {}." .format(name, age) print(string) #Your name is Nick, and your age is 28. ``` ### Formatting 格式化輸出 #### 文字 ```py= '''Example''' if __name__ == "__main__": print("{} {}".format("twilight", "whispers")) # 按順序輸出: twilight whispers print("{1} {0}".format("twilight", "whispers")) # 指定順序輸出: whispers twilight print("{obj} {act}".format(obj = "twilight", act = "whispers")) # 指定參數命名: twilight whispers word_dic = {"obj": "twilight", "act": "whispers"} print("{obj} {act}".format(**word_dic)) # 通過dictionary設定參數: twilight whispers word_list = ["twilight", "whispers"] print("{0[0]} {0[1]}".format(word_list)) # 通過list設定: twilight whispers print("{[0]} {[1]}".format(word_list)) # IndexError ``` #### 數字 %變數 ```py= '''Example''' print("pi is %d"%(3.14159)) #pi is 3 print("pi is %f"%(3.14159)) #pi is 3.141590 print("pi is %s"%(3.14159)) #pi is 3.14159 print("pi is %s"%('3.14159')) #pi is 3.14159 print("pi is %f"%('3.14159')) #TypeError ``` {序號 : 位元數 . 小數點第幾位 f } ```python= '''Example''' print("pi is {:.2f}".format(3.14159)) #pi is 3.14 print("pi is {1:.2f}, area is {0}.".format(1.325, 3.14159)) #pi is 3.14, area is 1.325. print("pi is {0:5.2f}, area is {1:5.1f}.".format(3.14159, 1.325)) #pi is 3.14, area is 1.3. ``` ### 逃脫字元 | \n | \\\ | \\' | \\" | \\a | \\b | |:---:|:---:|:---:|:---:|:---:|:---:| |Linefeed|Backslash|Single quote|Double quote|Bell|Backspace| | \f | \r | \t | \v | \ooo | \xhh | |:---:|:---:|:---:|:---:|:---:|:---:| |Formfeed|Carriage return|Horizontal tab|Vertical tab|character with octal valce ooo|character with hex valce hhh| ### 字串相關函式 不會改變字串本身 #### ==upper()== & ==lower()== 轉換成大寫或小寫 ```python= '''Example''' s = "A wanderer isn\'t always lost" print(s.upper()) #A WANDERER ISN'T ALWAYS LOST print(s.lower()) #a wanderer isn't always lost ``` #### ==startswith('')== & ==endswith('')== 檢查開頭和結尾 ```python= '''Example''' s = "A wanderer isn\'t always lost" print(s.startswith('always')) #False print(s.startswith('A')) #True print(s.endswith('lost')) #True ``` #### ==isdigit()== 檢查是否為數字組成 ```python= '''Example''' s = "A wanderer isn\'t always lost" print(s.isdigit()) #False ``` #### ==find('')== & ==replace(*a*,*b*)== 尋找和置換 ```python= '''Example''' s = "A wanderer isn\'t always lost" print(s.find('always')) #17 print(s.find('often')) #-1 print(s.replace('isn\'t always',' never')) #A wanderer never lost ``` #### ==split()== 切割 ```python= '''Example''' s = "A wanderer isn\'t always lost" print(s.split(' ')) #['A', 'wanderer', "isn't", 'always', 'lost'] print(s.split()) #['A', 'wanderer', "isn't", 'always', 'lost'] print(s.split(',')) #["A wanderer isn't always lost"] ``` #### ==strip()== 去除頭尾不需要的空白字串 ```python= '''Example''' s = " Never await victory " print(s.strip()) #Never await victory print(s) # Never await victory ``` ## 程式錯誤 ### Syntax Error ```python= '''Example''' radius = int(input("The radius?") #int缺少一個')' area = radius**2*3.14 print(area) ``` ### Execution Error ```python= '''Example''' radius = int(input("The radius?")) #此時輸入float就會發生ERROR area = radius**2*3.14 print(area) ``` ### Logic Error ```python= '''Example''' radius = int(input("The radius?")) area = radius**2*3.14 #應為area = radius**radius*3.14 print(area) ``` ### Bad Code 不容易閱讀的程式碼 ## 註解Comment ### 區塊註解 Block Comment * single quote ```python= ''' comment here ''' ``` * double quote ```python= """ comment here """ ``` ### 單行註解 Inline Comment * hash mark ```python= # comment here ``` ## 讀檔案 ### 讀一行 ```python= '''Example''' with open("file_name") as f: aLine = f.readline() ``` ### 逐行讀 ```python= '''Example''' with open("file_name") as f: for aLine in f: print(aLine) ``` # 邏輯運算 ==請務必縮排整齊,不要空白鍵和tab鍵混用。== * 循序 * 分支 * [if](#if) * [else](#if-else) * [elif](#elif) * 迴圈 * [while](#while) * [for ... in list](#for-i-in-list) * [for range](#for-i-in-rangestart-end-gap) ### 判斷布林值 | 型別 | False | True | | :------: | :------: | :-----: | | int, float, 複數 | 0, 0.0, 0+0j | 除了false以外的 | | str | 空白字串:'' | 除了false以外的 | | list, tuple, dict | 空白集合: list(), tuple(), dict{} | 除了false以外的 | ## ==if== #### if *condition*: ![](https://i.imgur.com/r0fEgqo.jpg) ```python= '''Example''' g = 20 if g >= 60: print("good") print("end") ``` ## ==if else== #### else: ![](https://i.imgur.com/K6vBt7z.jpg) ```python= '''Example''' g = 20 if g >= 60: print("pass") else: print("fail") print("end") ``` ### 條件性變數指定 ```python= '''Example''' price = 80 decide = 'buy' if price<100 else 'sell' print(decide) #buy ``` ## ==elif== #### elif *condition*: ![](https://i.imgur.com/ODYpIpU.jpg) ```python= '''Example''' g = 20 if g >= 60: print("pass") elif g >= 50: print("almost pass") else: print("fail") print("end") ``` ### Nasted if 巢狀 ## ==while== #### while *condition*: ```pseudo= '''Example''' counter = 0 #設定初始值 while condition: action counter = counter+1 #如果沒有,就是無窮迴圈 ``` ![](https://i.imgur.com/V7mEBG3.jpg) ```python= '''Example''' sum = 0; grade = 0 while grade != -999: sum += grade grade = int(input("input your grade:")) print("total is", sum) ``` ## ==for== #### for *i* in *list*: ```python= '''Example''' summary = 0 x = [20, 30, 90, 80] #List for g in x: summary = summary+g print(summary) ``` #### for *i* in range(*start*, *end*, *gap*) ex: range(1, 11, 2) ->[1, 3, 5, 7, 9] ex: range(10, 1, 1) ->回傳一個空資料集,因為沒辦法用1遞減 ```python= '''Example''' for i in range(4): print(str(i), end = '') #0123 ``` ```python= '''Example''' for i in range(4): for j in range(i+1): print("*", end = '') print() ''' * ** *** **** ''' ``` #### ==for *index*, *x* in enumerate(*list*):== ```python= '''Example''' n = [10, 34, 67, 34, 225] for i, x in enumerate(n): print(i," : ", x) #0 : 10 #1 : 34 #2 : 67 #3 : 34 #4 : 225 ``` ### ==break== 跳出迴圈 ```python= '''Example''' """比較兩個程式有沒有break的差異""" #檢查是不是質數 import time x = 2000000 isPrime = True t1 = time.time() #抓取時間 for i in range(2, x): if x%i == 0: isPrime = False print(x, "is Prime?", isPrime) #2000000 is Prime? False t2 = time.time() print("\nComputing time: ", t2-t1) #Computing time: 0.1817002296447754 import time x = 2000000 isPrime = True t1 = time.time() #抓取時間 for i in range(2, x): if x%i == 0: isPrime = False break print(x, "is Prime?", isPrime) #2000000 is Prime? False t2 = time.time() print("\nComputing time: ", t2-t1) #Computing time: 0.0004584789276123047 ``` #### ==for else break== 若for loop裡都沒有執行break就會執行else ```python= '''Example''' #列出100以下的所有質數 n = 100 print("The Prime numbers below {} are:".format(n)) for x in range(2, n+1): for d in range(2, x): if x%d == 0: break #代表x不是質數 else: #代表x是質數 print(x, end = ' ') #The Prime numbers below 100 are: #2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ``` ### ==continue== 直接跳往下一個,忽略剩餘程式重新開始 ```python= '''Example''' for i in range(4): if i == 2: continue print(i) #0 #1 #3 ``` ### and &any ```python= '''Example''' c = [True, False, True] if any(c): #其中一個為真,就會進來 if all(c): #全部為真,就會進來 if not all(c) and any(c): #至少一個為真但不全部為真 ``` ### import random #### ==random.randint(*a*, *b*)== 從a~b裡隨機選數 #### ==random.choice(*List*)== 從List裡隨機選一個資料 ## 實作 ### 韓信點兵 未知數n,除3餘2,除5餘3,除7餘2 ```python= n = 2 while True: c1 = (n%3) == 2 c2 = (n%5) == 3 c3 = (n%7) == 2 if (c1 and c2 and c3): print(n) #23 break n = n+1 ``` ### turtle 套件 ```python= """畫一個正方形""" import turtle tina = turtle.Turtle() #產生一個箭頭叫tina tina.shape('turtle') #設定tina的形狀是個烏龜 tina.forward(100) #往前100 tina.right(90) #右轉90度 tina.forward(100) tina.right(90) tina.forward(100) tina.right(90) tina.forward(100) tina.right(90) ``` ```python= """畫一個星星""" import turtle as tu tu.color('red', 'yellow') #改變畫筆顏色,可以用字串或是16進位 tu.begin_fill() #填滿顏色 while True: tu.forward(200) tu.left(70) if abs(tu.pos())<1: break tu.end_fill #先呼叫gegin_fill就可以填滿顏色 tu.done() ``` ```python= """畫一個螺旋""" import turtle mystamp = turtle.Turtle(visible = False) mystamp.shape("turtle") mystamp.color("blue") mystamp.speed(8) #改變速度 mystamp.penup() #提起筆,移動時不會有痕跡 stepLen = 20 for i in range(31): mtstamp.stamp() stepLen = stepLen+3 mystamp.forward(stepLen) mystamp.right(24) mystamp.penup() mystamp.goto(0, 260) #goto(x座標, y座標) mystamp.color('red') mystamp.write("Done!", align = 'center', font = ('Arial', 20, 'bold')) #顯示字串 ``` ### 猜數字 ```python= """隨機生成一個數,使用者要來猜這個數字""" import random cmp = random.randint(1, 100) correct = False while not correct: guess = input("Guess a number between 1~100") if not guess.isdigit(): print("Must be a number") continue guess = int(guess) if not (guess >= 1 and guess <=100): print("Must between 1~100") continue if cmp == guess: print("Correct!!") correct = True elif cmp > guess: print("Guess a larger number") else: print("Guess a smaller number") ``` # 集合物件 || List | Tuple | Set | Dict | |:------:|:------:|:------:|:------:|:------:| |順序|○|○|✕|✕| |重複|○|○|✕|✕| |瀏覽|○|○|○✕|○| |修改|○|✕|○|○| |允許不同型態|○|○|○|○| ## List ### 建立 ```python= '''Example''' clan = ['Venture', 'Brujah', 'Nosferatu'] age = [2300, 300, 1043] data = ['Edrict',['Toreador', 862, 'enchanter']] #list裡面放list ``` #### 空集合 ```python= lst = [] ``` #### 生成式 Comprehension newList = [運算式 for 區域變數 in 容器 if 條件] ```python= '''Example''' lst = [i for i in range(0,10,2)] print(lst) #[0, 2, 4, 6, 8] ``` ```python= '''Example''' """square_1和square_2式一樣的list""" square_1 = [] for i in range(10): if i%2 == 0: square_1.append(i**2) print(square_1) #[0, 4, 16, 36, 64] square_2 = [i**2 for i in range(10) if i%2 == 0] print(square_2) #[0, 4, 16, 36, 64] ``` ### 新增 #### ==.append(*element*)== 在list的後面新增一個element ```python= '''Example''' flavors = ['Choco'] flavors.append('Vanilla') print(flavors) #['Choco', 'Vanilla'] ``` #### ==.expend(*list*)== 從後面新增一個list ```python= '''Example''' flavors = ['Choco', 'Vanilla'] another = ['Lemon', 'Cola', 'Grape'] flavors.extend(another) print(flavors) #['Choco', 'Vanilla', 'Lemon', 'Cola', 'Grape'] ``` #### ==.insert(*index*, *element/list*)== 在指定位置插入一個element/list,其他後移。 ```python= '''Example''' flavors = ['Choco', 'Vanilla', 'Lemon', 'Cola', 'Grape'] another = ['Strawberry', 'Cream'] flavors.insert(0, 'Orange') print(flavors) #['Orange', 'Choco', 'Vanilla', 'Lemon', 'Cola', 'Grape'] flavors.insert(3, another) print(flavors) #['Orange', 'Choco', 'Vanilla', ['Strawberry', 'Cream'], 'Lemon', 'Cola', 'Grape'] ``` ### 刪除 #### ==.remove(*element*)== 移除元素,若有重複則移除第一個。 ```python= '''Example''' dessert = ['tiramisu', 'black forest', 'brownie', 'puff', 'scone', 'puff', 'macaron', 'gelato'] dessert.remove('puff') print(dessert) #['tiramisu', 'black forest', 'brownie', 'scone', 'puff', 'macaron', 'gelato'] dessert.remove('black forest') print(dessert) #['tiramisu', 'brownie', 'scone', 'puff', 'macaron', 'gelato'] ``` #### ==.pop(*index*)== 移除並回傳,沒有指定時則默認為最後一個。 ```python= '''Example''' dessert = ['tiramisu', 'brownie', 'scone', 'puff', 'macaron', 'gelato'] basket = dessert.pop(4) print(dessert) #['tiramisu', 'brownie', 'scone', 'puff', 'gelato'] print(basket) #'macaron' basket = dessert.pop() print(dessert) #['tiramisu', 'brownie', 'scone', 'puff'] print(basket) #'gelato' ``` #### ==del *list*[*index*]== delete,刪除。 ```python= '''Example''' dessert = ['tiramisu', 'brownie', 'scone', 'puff'] del dessert[0] print(dessert) #['brownie', 'scone', 'puff'] ``` #### ==.clear()== 刪除所有資料 ```python= '''Example''' dessert = ['tiramisu', 'brownie', 'scone', 'puff'] dessert.clear() print(dessert) #[] ``` ### 修改 #### 指定修改 直接指定index進行修改。 ```python= '''Example''' flower = ['camellia', 'freesia', 'kapok', 'orchid', 'tulip'] flower[2] = 'peony' print(flower) #['camellia', 'freesia', 'peony', 'orchid', 'tulip'] ``` #### ==list_1 **is** list_2== 比較兩個list是否參考(reference)相同。 #### ==list_1 == list_2== 比較兩個list是否內容相同。 ```python= '''Example''' flower = ['camellia', 'freesia', 'peony', 'orchid', 'tulip'] f = flower #相同參考 #檢查是否相同參考 print(flower is f) #True #檢查是否相同值(內容相同) print(flower == f) #True Flowers = flower.copy() #不同參考,相同值 Flowers[3] = 'lilac' #檢查是否相同參考 print(flower is Flowers) #False #檢查是否相同值(內容相同) print(flower == Flowers) #False ``` ### 查詢瀏覽 #### ==list[*index*]== 取得該index的值。 ```python= '''Example''' metal = ['sodium', 'iron', 'nickel', 'zinc', 'silver'] print(metal[3]) #'zinc' ``` |element|'sodium'|'iron'|'nickel'|'zinc'|'silver'| | :-----: | :-----: | :-----: | :-----: | :-----: | :-----: | |index|0|1|2|3|4| #### ==list[start: end+1: step]== 擷取start到end的資料。 ```python= '''Example''' num = [52, 88, 91, 12, 75, 91] print(num[0:3]) #[52, 88, 91] #省略start時,默認為0 print(num[:3]) #[52, 88, 91] #省略end時,擷取到最後一個 print(num[3:]) #[12, 75, 91] #倒數第一個 print(num[-1]) #91 #一次跳兩個 print(num[::2]) #[52, 91, 75] print(num[-1:-2]) #[] ``` |element|52|88|91|12|75|91| |:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:| |[ 1 : 3 ]||├─|─┤|||| |[ 1 : ]||├─|──|──|──|─┤| |[ : 3 ]|├─|──|─┤|||| #### ==element in list== 回傳elemwnt是否存在這個list中。 ```python= '''Example''' metal = ['sodium', 'iron', 'nickel', 'zinc', 'silver'] print('nickel' in metal) #True print('copper' in metal) #False ``` #### ==for index, x in enumerate(list)== 走訪list。 ```python= '''Example''' metal = ['sodium', 'iron', 'nickel', 'zinc', 'silver'] for i, x in enumerate(metal): print(i ,':', x) #0 : sodium #1 : iron #2 : nickel #3 : zinc #4 : silver ``` #### ==.count(element)== 回傳此element的個數。 ```python= '''Example''' metal = ['sodium', 'iron', 'nickel', 'zinc', 'silver', 'iron'] print(metal.count('iron')) #2 ``` #### ==.index(element)== 回傳此資料中第一個該element的index。 ```python= '''Example''' metal = ['sodium', 'iron', 'nickel', 'zinc', 'silver', 'iron'] print(metal.index('silver')) #4 ``` #### ==len(data)== 回傳data的長度。 ```python= '''Example''' metal = ['sodium', 'iron', 'nickel', 'zinc', 'silver', 'iron'] print(len(metal)) #6 ``` #### ==max(data) & min(data)== 回傳data中最大或最大的element。 #### ==sum(data)== 回傳data內所有數值的總和。 ```python= '''Example''' num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(len(num)) #10 print(max(num)) #9 print(min(num)) #0 print(sum(num)) #45 ``` ### 排序 #### ==.sort(parameter)== 排序,會改變list。 * 參數parameter * reverse = False:省略則默認為此,代表由小排到大 * reverse = True:由大排到小 ```python= '''Example''' number = [24, 54, 95, 100, 73, 52, 19] number.sort() print(number) #[19, 24, 52, 54, 73, 95, 100] number.sort(reverse=True) print(number) #[100, 95, 73, 54, 52, 24, 19] element = ['oxygen', 'nitrogen', 'hydrogen', 'carbon', 'fluorine'] element.sort() print(element) #['carbon', 'fluorine', 'hydrogen', 'nitrogen', 'oxygen'] ``` #### ==sorted(list, parameter)== 功能、參數和sort相同,但不改變原本list。 ```python= '''Example''' number = [24, 54, 95, 100, 73, 52, 19] print(sorted(number)) #[19, 24, 52, 54, 73, 95, 100] print(sorted(number, reverse=True)) #[100, 95, 73, 54, 52, 24, 19] element = ['oxygen', 'nitrogen', 'hydrogen', 'carbon', 'fluorine'] print(sorted(element)) #['carbon', 'fluorine', 'hydrogen', 'nitrogen', 'oxygen'] print(sorted(element, reverse=True)) #['oxygen', 'nitrogen', 'hydrogen', 'fluorine', 'carbon'] ``` #### ==.reverse()== 前後順序顛倒 ```python= '''Example''' number = [24, 54, 95, 100, 73, 52, 19] number.reverse() print(number) #[19, 52, 73, 100, 95, 54, 24] element = ['oxygen', 'nitrogen', 'hydrogen', 'carbon', 'fluorine'] element.reverse() print(element) #['fluorine', 'carbon', 'hydrogen', 'nitrogen', 'oxygen'] ``` ### 氣泡排序 Bubble Sort 兩個資料倆倆比較,符合條件互換, 進行數回合直到比較完成,共s筆資料需要進行(s-1)回合。 ```python= '''Example''' a = [300, 108, 20, 256] s = len(a) r = s-1 for i in range(1, r+1): print('Round', i) for j in range (0, s-i): if a[j] > a[j+1]: temp = a[j] a[j] = a[j+1] a[j+1] = temp print(a) ''' Round 1 [108, 20, 256, 300] Round 2 [20, 108, 256, 300] Round 3 [20, 108, 256, 300] ''' ``` ### 二維list ```python= '''Example''' """建立一個3*3的二維list""" lst = [[a, b, c], [d, e, f], [g, h, i]] ``` #### ==zip()== ```python= '''Example''' flavor = ['pu\'er tea', 'sencha', 'jalapeno papper'] base = ['rum', 'whiskey', 'tequila'] infusion = zip(flavor, base) print(infusion) #<zip object at 0x7f16740ba320> infusion = list(infusion) print(infusion) #[("pu'er tea", 'rum'), ('sencha', 'whiskey'), ('jalapeno papper', 'tequila')] ``` #### 新增append ```python= '''Example''' lst = [['0, 0', '0, 1', '0, 2'], ['1, 0', '1, 1', '1, 2']] lst.append( ['2, 0', '2, 1', '2, 2']) # 新增一"個"元素 print(lst) # [['0, 0', '0, 1', '0, 2'], ['1, 0', '1, 1', '1, 2'], ['2, 0', '2, 1', '2, 2']] lst[0].append('0, 3') print(lst) #[['0, 0', '0, 1', '0, 2', '0, 3'], ['1, 0', '1, 1', '1, 2'], ['2, 0', '2, 1', '2, 2']] ``` #### 刪除remove() ```python= '''Example''' lst = [['0, 0', '0, 1', '0, 2'], ['1, 0', '1, 1', '1, 2'], ['2, 0', '2, 1', '2, 2']] lst.remove('1, 2') # ValueError: list.remove(x): x not in list lst[1].remove('1, 2') print(lst) # [['0, 0', '0, 1', '0, 2'], ['1, 0', '1, 1'], ['2, 0', '2, 1', '2, 2']] lst.remove( ['2, 0', '2, 1', '2, 2']) print(lst) # [['0, 0', '0, 1', '0, 2'], ['1, 0', '1, 1']] ``` ## Tuple 和list幾乎一模一樣,但不能修改,因此可以避免錯誤的修改,更省空間、速度更快,可以做為Dictionary的key。 ### 建立 ```python= '''Example''' tup = (1, 2, 3, 4, 5) tup2 = "a", "b", "c", "d" tup3 = tuple([1, 2, 3, 4, 5]) #由list建立 tup4 = (3, 4)*2 #(3, 4, 3, 4) ``` ### 不可以新增、刪除、修改 ```python= '''Example''' tup = (1, 2, 3) tup[0] = 0 #ERROR ``` ```python= '''Example''' tup = (3, 8, 1, 2, 0, 2, 7) tup = tup + (6) #ERROR tup = tup + tuple([6]) print(tup) #(3, 8, 1, 2, 0, 2, 7, 6) ``` ### 更省空間、速度更快 ```python= '''Example''' """tuple更省空間""" import sys lst = [11, 22, 99, 35, 59] tup = (11, 22, 99, 35, 59) #抓取兩資料相同的List&Tuple print(sys.getsizeof(lst)) #112 print(sys.getsizeof(tup)) #96 ``` ```python= '''Example''' """tuple速度更快""" import timeit do_lst = timeit.timeit(stmt = '[11, 22, 99, 35, 59]', number = 10000000) do_tup = timeit.timeit(stmt = '(11, 22, 99, 35, 59)', number = 10000000) print(do_lst) #0.6791820189999953 print(do_tup) #0.10594103799996901 ``` ### 查詢瀏覽 和list一樣。 ```python= '''Example''' tup = (3, 8, 1, 2, 0, 2, 7) print(tup[0]) #3 print(tup(1: 4)) #ERROR print(tup[1: 4]) #(8, 1, 2) print(tup[-2]) #2 print(len(tup)) #7 print(tup.count(2)) #2 print(tup.index(0)) #4 tup = tup + (6) #ERROR tup = tup + tuple([6]) print(tup) #(3, 8, 1, 2, 0, 2, 7, 6) ``` ### 排序 ```python= '''Example''' """一維tuple的排序""" tup = ('acorn', 'teak', 'ginkgo', 'juniper') sortTup = sorted(tup) print(sortTup) #['acorn', 'ginkgo', 'juniper', 'teak'] ``` ```python= '''Example''' """二維tuple的排序,以第一個為準""" tup = [(36, 18), (46, 73), (13, 2)] sortTup = sorted(tup) print(sortTup) #[(13, 2), (36, 18), (46, 73)] ``` ### Unpacking ```python= '''Example''' person = ('female', 25, 'Eleanor') (sex, age, surname) = person #一個蘿蔔一個坑 print(sex, age, surname) #female 25 Eleanor person = ('male', 28, 'Earl') sex, age, surname = person print(sex, age, surname) #male 28 Earl sex, age = person #ERROR ``` ## Set 數學上的集合:不能重複,也沒有順序,方便作集合的運算。 ### 建立 ```python= '''Example''' wood = {'locust', 'oak', 'pine', 'spruce'} wood2 = set(['locust', 'oak', 'pine', 'spruce']) ``` ```python= '''Example''' """不能重複""" wood = {'yew', 'willow', 'cone', 'fir', 'yew'} print(wood) #{'fir', 'yew', 'cone', 'willow'} """沒有順序""" wood = {'fir', 'yew', 'cone', 'willow'} print(wood[0]) #ERROR #TypeError: 'set' object is not subscriptable ``` #### 空Set ```python= emptySet = set() emptyDict = {} ``` ### 新增 #### ==.add(element)== ```python= '''Example''' liqueur = {'Bailey\'s', 'Campari', 'Jager'} liqueur.add('Cointreau') liqueur.add('Cointreau') #不再新增,但也不會有ERROR print(liqueur) #{'Campari', "Bailey's", 'Jager', 'Cointreau'} ``` ### 刪除 #### ==.remove(element)== ```python= '''Example''' grape = {'Chardonnay', 'Riesling', 'Merlot', 'Shiraz', 'Grenache'} grape.remove('Riesling') print(grape) #{'Merlot', 'Grenache', 'Shiraz', 'Chardonnay'} grape.remove('Riesling') #ERROR #KeyError: 'Riesling' ``` #### ==.pop(element)== ```python= '''Example''' grape = {'Chardonnay', 'Nebbiolo', 'Merlot', 'Shiraz', 'Grenache'} one = grape.pop() print(grape) #{'Nebbiolo', 'Grenache', 'Shiraz', 'Chardonnay'} print(one) #Merlot two = grape.pop('Shiraz') #ERROR #TypeError: pop() takes no arguments (1 given) ``` #### ==.discard(element)== ```python= '''Example''' grape = {'Chardonnay', 'Nebbiolo', 'Malbec', 'Shiraz', 'Grenache'} grape.discard('Riesling') #避免產生例外 print(grape) #{'Nebbiolo', 'Grenache', 'Shiraz', 'Chardonnay', 'Malbec'} grape.discard('Chardonnay') print(grape) #{'Nebbiolo', 'Grenache', 'Shiraz', 'Malbec'} ``` #### ==.clear()== 刪除全部。 ```python= '''Example''' grape = {'Nebbiolo', 'Malbec', 'Shiraz', 'Grenache'} grape.clear() print(grape) #set() ``` ### 查詢瀏覽 #### ==len(set)== ```python= '''Example''' base = {'Vodka', 'Gin', 'Rum', 'Tequila', 'Whuskey', 'Brandy'} print(len(base)) #6 ``` #### ==element in set== ```python= '''Example''' base = {'Vodka', 'Gin', 'Rum', 'Tequila', 'Whuskey', 'Brandy'} print('Gin' in base) #True print('Bitter' in base) #False ``` #### ==for element in set:== ```python= '''Example''' base = {'Vodka', 'Gin', 'Rum', 'Tequila', 'Whuskey', 'Brandy'} for i in base: print(i) #Tequila #Rum #Gin #Whuskey #Brandy #Vodka ``` ### 排序 因為沒有順序,排序後會變成list。 ```python= '''Example''' base = {'Vodka', 'Gin', 'Rum', 'Tequila', 'Whuskey', 'Brandy'} print(sorted(base)) #['Brandy', 'Gin', 'Rum', 'Tequila', 'Vodka', 'Whuskey'] print(type(sorted(base))) #<class 'list'> ``` ### Set Operations #### 聯集 * set_1 | set_2 * set_1.union(set_2) ```python= '''Example''' one = {1, 2, 3, 4, 5} two = {3, 4, 5, 6, 7} print(one | two) #{1, 2, 3, 4, 5, 6, 7} print(one.union(two)) #{1, 2, 3, 4, 5, 6, 7} ``` #### 交集 * set_1 & set_2 * set_1.intersection(ser_2) ```python= '''Example''' one = {1, 2, 3, 4, 5} two = {3, 4, 5, 6, 7} print(one & two) #{3, 4, 5} print(one.intersection(two)) #{3, 4, 5} ``` #### 差集 * set_1 - set_2 * set_1.difference(set_2) ```python= '''Example''' one = {1, 2, 3, 4, 5} two = {3, 4, 5, 6, 7} print(one - two) #{1, 2} print(one.difference(two)) #{1, 2} print(two - one) #{6, 7} print(two.difference(one)) #{6, 7} ``` ## Dict 由key和value所組成的集合,不可重複,沒有順序,可以自訂索引值。 ### 建立:=={key: value}== ```python= '''Example''' mojito = {'base':'Rum', 'sour':'lemon', 'sugar':'simple syrup', 'smell':'mint'} margarita = dict(base = 'Tequila', ligueur = 'Cointreau', sour = 'lemon') print(margarita) #{'base': 'Tequila', 'ligueur': 'Cointreau', 'sour': 'lemon'} ``` ```python= """key必須是immutable,可以是int、string、tuple,不能是list""" '''Example''' dict1 = {1:92, 2:56, 3:73} dict2 = {'Chloe':78, 'Audrey':81} dict3 = {('Frankie', 'math'):43, ('Becky', 'eng'):94} dict4 = {['phy']:46, ['math']:13} #ERROR #TypeError: unhashable type: 'list' ``` ```python= '''Example''' """List裡是Tuple,第一個元素為key""" tup = [('base','Gin'),('bobble','Tonic water')] gintonic = dict(tup) print(gintonic) #{'base': 'Gin', 'bobble': 'Tonic water'} ``` #### 空dict ```python= empty = {} empty = dict() ``` #### Dictionary Comprehension ```python= '''Example''' """創造一個dict,key是cocktail,value是各單字長度""" cocktail = ['God Father', 'Old-Fashioned', 'Sidecar'] cocktail_len = {c: len(c) for c in cocktail} print(cocktail_len) #{'God Father': 10, 'Old-Fashioned': 13, 'Sidecar': 7} ``` ```python= '''Example''' white = ['Muscat', 'Chardonnay', 'Riesling'] red = ['Cabernet Sauvignon', 'Pinot Noir', 'Gamay', 'Merlot'] wine = [white, red] wine_count = {tuple(w): len(w) for w in wine} print(wine_count) #{('Muscat', 'Chardonnay', 'Riesling'): 3, ('Cabernet Sauvignon', 'Pinot Noir', 'Gamay', 'Merlot'): 4} ``` ```python= '''Example''' flavor = ['coco', 'jasmine', 'cocoa bean'] base = ['whiskey', 'gin', 'vodka'] infusion = {k: v for (k,v) in list(zip(flavor, base))} print(infusion) #{'coco': 'whiskey', 'jasmine': 'gin', 'cocoa bean': 'vodka'} ``` ### 新增 #### ==dict[key] = value== ```python= '''Example''' bacardi = {'base':'Rum', 'sour':'lime'} bacardi['sugar'] = 'grenadine' print(bacardi) #{'base': 'Rum', 'sour': 'lime', 'sugar': 'grenadine'} ``` ### 刪除 #### ==del dict[key]== ```python= '''Example''' rickey = {'base':'Gin', 'sour':'lime', 'bobble':'soda', 'flavor':'cucumber', 'taste':'mint'} del rickey['taste'] print(rickey) #{'base': 'Gin', 'sour': 'lime', 'bobble': 'soda', 'flavor': 'cucumber'} ``` #### ==.pop(key)== ```python= '''Example''' rickey = {'base':'Gin', 'sour':'lime', 'bobble':'soda', 'flavor':'cucumber'} flavor = rickey.pop('flavor') print(rickey) #{'base': 'Gin', 'sour': 'lime', 'bobble': 'soda'} print(flavor) #cucumber ``` ### 修改 #### ==dict[key] = value== 判斷已有的key,會直接覆蓋 ```python= '''Example''' longbeach = {'base':'longisland', 'flavor':'cola'} longbeach['flavor'] = 'cranberry' print(longbeach) #{'base': 'longisland', 'flavor': 'cranberry'} ``` #### ==.update({key: value})== ```python= '''Example''' tokyo = {'base':'longisland', 'flavor':'cola'} tokyo.update({'flavor':'Midorl'}) print(tokyo) #{'base': 'longisland', 'flavor': 'Midorl'} ``` ### 查詢瀏覽 #### ==dict[key]== ```python= '''Example''' tequilaSunrise = {'base':'tequila', 'sour':'lemon', 'sugar':'grenadine', 'flavor':'orange'} print(tequilaSunrise['sugar']) #grenadine ``` #### ==len(dict)== ```python= '''Example''' tequilaSunrise = {'base':'tequila', 'sour':'lemon', 'sugar':'grenadine', 'flavor':'orange'} print(len(tequilaSunrise)) #4 ``` #### ==key in dict== ```python= '''Example''' tequilaSunrise = {'base':'tequila', 'sour':'lemon', 'sugar':'grenadine', 'flavor':'orange'} print('base' in tequilaSunrise) #True print('bobble' in tequilaSunrise) #False ``` #### ==.keys()== ```python= '''Example''' matador = {'base':'Tuquila', 'sour':'lime', 'flavor':'pineapple'} k = matador.keys() print(k) #dict_keys(['base', 'sour', 'flavor']) print(type(k)) #<class 'dict_keys'> ``` #### ==.values()== ```python= '''Example''' matador = {'base':'Tuquila', 'sour':'lime', 'flavor':'pineapple'} v = matador.values() print(v) #dict_values(['Tuquila', 'lime', 'pineapple']) print(type(v)) #<class 'dict_values'> ``` #### ==.items()== 取出一群tuple。 ```python= '''Example''' matador = {'base':'Tuquila', 'sour':'lime', 'flavor':'pineapple'} i = matador.items() print(i) #dict_items([('base', 'Tuquila'), ('sour', 'lime'), ('flavor', 'pineapple')]) print(type(i)) #<class 'dict_items'> ``` ### 排序 ## 實作 # 函式 ## 模組化設計 ### ==define== ```python= def function_name(argument): '''docstring''' function return value ``` * def:保留字,define * argument:參數,多個以' , '分開,可省略 * docstring:用來解釋此函式的用法和意義,用help()呼叫,可省略 * return value:回傳值,可省略 ```python= '''Example''' def max_function(a, b, c): '''get max value''' if a > b: if a > c: m = a else: m = c elif b > c: m = b else: m = c return c help(max_function) """ Help on function max_function in module __main__: max_function(a, b, c) get max value """ print(max_function(1, 2, 3)) #3 ``` ### 參數 #### 必要參數 required argument 必要的,不可缺。 #### 選要參數 default argument/optional argument 非必要的,若無傳入則以所宣告的預設值為值。 ==agrument = vallue== ```python= '''Example''' def prime(n, start = 2): '''get the prime number between start & n''' if start < 2: start = 2 for x in range(start, n+1): for d in range(2, x): if x%d == 0: break #x is not prime else: print(x, end = ' ') print(prime()) #ERROR;n為必要參數 #TypeError: prime() missing 1 required positional argument: 'n' print(prime(10)) #2 3 5 7 print(prime(10, 5)) #5 7 print(prime(10, start = 5)) #5 7 print(prime(start = 5, 10)) #ERROR:必要參數一定要在選要參數前面 #SyntaxError: positional argument follows keyword argument ``` ```python= '''Example''' def prime(start = 2, end = 20): '''get the prime number between start & end''' if start < 2: start = 2 for x in range(start, end+1): for d in range(2, x): if x%d == 0: break #x is not prime else: print(x, end = ' ') print(prime()) #2 3 5 7 11 13 17 19 print(prime(2, 10)) #2 3 5 7 print(prime(end = 20, start = 10)) #11 13 17 19 ``` #### 變動長度參數 ==*agrument== ```python= '''Example''' def avg(name, *grade): summary = 0 print("grade's type is {}, value is {}".format(type(grade), grade)) for g in grade: summary += g if grade != (): avg = summary // len(grade) print(name + "'s average:", avg) else:'''Example''' def ten(g): for i, x in enumerate(g): g[i] = g[i]+10 grade = 50 #1. print(id(grade)) #94789248131104 ten(grade) #2. print('grade = ', grade) #grade = 50 print(name + " has no grade") print(avg('Gloria', 85, 76, 92)) #grade's type is <class 'tuple'>, value is (85, 76, 92) #Gloria's average: 84 print(avg('Casey')) #grade's type is <class 'tuple'>, value is () #Casey has no grade ``` ### 參數傳遞 #### Immutable object不可變動物件 ex:int, string 假如 a = 1,a儲存了一個倉號,當 a = 2 時,是倉號換了,但倉號內的物件不換。 ```python= '''Example''' a = 1 print(id(a)) #94789248129536 a = 2 print(id(a)) #94789248129568 a = 3 print(id(a)) #94789248129600 b = 3 print(id(b)) #94789248129600 ``` #### Mutable Object可變動物件 ex:list ```python= '''Example''' m = [1, 2] print(id(m)) #139734412252736 m[0] = 3 print(id(m)) #139734412252736 print(m) #[3, 2] ``` #### Pass by Reference * Immutable object ```python= '''Example''' def ten(g): print(id(g)) #94789248131104 g = g+10 #3. print(id(g)) #94789248131424 print('g = ', g) #g = 60 grade = 50 #1. print(id(grade)) #94789248131104 ten(grade) #2. print('grade = ', grade) #grade = 50 ``` ![](https://i.imgur.com/vLL6Na3.jpg) * Mutable Object ```python= '''Example''' def ten(g): for i, x in enumerate(g): g[i] = g[i]+10 print('function內: ', g) #function內: [60, 80] grade = [50, 70] ten(grade) print('呼叫端:', grade) #呼叫端: [60, 80] ``` ```python= '''Example''' def ten(g): for i, x in enumerate(g): g[i] = g[i]+10 print('function內: ', g) #function內: [60, 80] grade = [50, 70] ten(grade.copy()) print('呼叫端:', grade) #呼叫端: [50, 70] ``` ## Lambda Function 可以沒有名字的函式,一定要有回傳值和參數,並且不可以換行。 ```python= function_name = lambda argument : methods #':'代表執行 ``` ```python= '''Example''' def avg1(eng, math, phy): return round((eng + math + phy)/3, 2) print(avg1) #<function avg1 at 0x7f167400e8c0> avg2 = lambda eng, math, phy : round((eng + math + phy)/3, 2) print(avg2) #<function <lambda> at 0x7f167400e440> a = avg1(65, 94, 47) b = avg2(65, 94, 47) print(a, b) #68.67 68.67 ``` ### 排序時用lambda來指定key ```python= '''Example''' grade = [[77, 28, 23], [46, 100, 45], [79, 82, 94]] #二維list會依照第一個排序 sortedGrade = sorted(grade) print(sortedGrade) #[[46, 100, 45], [77, 28, 23], [79, 82, 94]] #依照二維list裡的最後一個排序 sortedGrade = sorted(grade, key = lambda x : x[-1]) print(sortedGrade) #[[77, 28, 23], [46, 100, 45], [79, 82, 94]] #依總分排序 w = lambda x : x[0]*0.3 + x[1]*0.4 + x[2]*0.4 sortedGrade = sorted(grade, key = lambda x : w(x)) print(sortedGrade) #[[77, 28, 23], [46, 100, 45], [79, 82, 94]] ``` ### 把集合內的資料做轉換 ```python= '''Example''' import math a = [59, 67, 43, 100, 93, 88] print(map(lambda x : round(math.sqrt(x)*10, 2), a)) #<map object at 0x7f12bd980c50> print(list(map(lambda x : round(math.sqrt(x)*10, 2), a))) #[76.81, 81.85, 65.57, 100.0, 96.44, 93.81] ``` ### 把集合內的資料做篩選 ```python= '''Example''' import math a = [59, 67, 43, 100, 93, 88] print(filter(lambda x : x>=60, a)) #<filter object at 0x7f12b96e6950> print(list(filter(lambda x : x>=60, a))) #[67, 100, 93, 88] ``` ## 例外 ```python= try: #要做的動作 except Exception: #發生例外(Exception)所處理的動作 else: #沒發生例外要做的動作 finally: #不論有沒有例外都會做的動作 ``` ```python= '''Example''' def getAge(year): if year>2020 or year<1900: raise Exception('Impossible year') #拋出例外 return 2021-year while True: try: year = int(input('Your born year:')) age = getAge(year) except Exception as e: print(e) else: print('Your age:', age) break ``` ## 實作 # 資料處理 ## Pandas https://pandas.pydata.org/ ### 表格轉換 ```python= import pandas as pd Sniper_Rifle ={'name': ['Kar98K', 'M24', 'Win94', 'AWM', 'Mosion Nagant'], 'bullet': ['7.62 Soviet', '7.62 Soviet', '.45 ACP', '.300 Win Mag', '7.62 Soviet'], 'lethality': [79, 75, 66, 105, 79], 'max distance': [500, 800, 500, 1000, 1000]} df = pd.DataFrame(Sniper_Rifle) print(df) ``` ![image](https://hackmd.io/_uploads/ryA-mLmCp.png) #### 行列互換 ```python= df = pd.DataFrame(Sniper_Rifle).T print(df) ``` ![image](https://hackmd.io/_uploads/BJNwLUXCp.png) #### 直接指定index ```python= df = pd.DataFrame(Sniper_Rifle) df = df.set_index('name') print(df) ``` ![image](https://hackmd.io/_uploads/r1LSXIm0a.png) #### 自訂index ```python= df = pd.DataFrame(Sniper_Rifle, index = Sniper_Rifle['name']) #index 要是一個list #print(Sniper_Rifle['name']) # -> ['Kar98K', 'M24', 'Win94', 'AWM', 'Mosion Nagant'] print(df) ``` ![image](https://hackmd.io/_uploads/BkjcQ8XCT.png) ### 取用資料 ```python= df = pd.DataFrame(Sniper_Rifle) df = df.set_index('name') print(df) ``` ![image](https://hackmd.io/_uploads/HJbNxDmCp.png) #### 單個:指定行列名稱 ==.at[*row_name*, *column_name*]== ```python= print(df.at[ 'Kar98K', 'max distance']) # 500 print(df.at[ 'Win94', 'lethality']) # 66 print(df.at[ 'Mosion Nagant', 'bullet']) # 7.62 Soviet print(df.at[ 'bullet', 'M24']) # KeyError ``` #### 單個:指定行列數字 ==.**i**at[*row_index*, *column_index*]== ```python= print(df.iat[ 3, 0]) # .300 Win Mag print(df.iat[ 4, 1]) # 79 print(df.iat[ 0, 2]) # 500 print(df.iat[ 4, 3]) # IndexError ``` #### 列:指定列名稱 ==.loc[*row_name*]== ```python= print(df.loc['Win94']) ``` ![image](https://hackmd.io/_uploads/SyrFTIm0T.png) ```python= ''' 不只一筆 ''' print(df.loc['Win94': 'Mosion Nagant']) ``` ![image](https://hackmd.io/_uploads/SkgQ-v706.png) #### 列:指定列數字 ==.**i**loc[*row_index*]== ```python= print(df.iloc[3]) ``` ![image](https://hackmd.io/_uploads/SJ6gR8X06.png) ```python= ''' 不只一筆 ''' print(df.iloc[1: 3]) ``` ![image](https://hackmd.io/_uploads/HyR8Zv7Aa.png) #### 用陣列取得整組 ```python= ''' 不只一筆 ''' print(df.loc['Win94': 'Mosion Nagant', ['bullet', 'lethality']]) ``` ![image](https://hackmd.io/_uploads/SJ-x9wm0a.png) #### 行:指定行名稱 ==.*column_name*== ```python= print(type(df.bullet)) # <class 'pandas.core.series.Series'> print(df.bullet) ``` ![image](https://hackmd.io/_uploads/H1nRCIQ0T.png) #### #### 選擇數比 ### 表格資料處理 || C1 | C2 | C3 | | -------- | -------- | -------- | -------- | | R1 | Text | Text | Text | | R2 | Text | Text | Text | | R3 | Text | Text | Text | | R4 | Text | Text | Text | | R5 | Text | Text | Text | ### Excel相關 ``` ``` #### 選擇特定資料 ## 正規表達式 Regular Expression ### 通用字元 | 符號 | 意義 | | :--------: | :-------- | |\w|配對任一字母、數字或底線的字元| |\W|配對任一字母、數字或底線"以外"的字元| |\d|配對任意十進制數字| |\D|配對任意十進制數字"以外"的字元| |\s|配對任一空白字元| |\S|配對任一空白字元"以外"的字元| | . |配對除換行"以外"的字元| ```python= import re string = "javascriptcsshtml5python_and python2 isgoingtoGG" print(re.findall("\w\dpython\w", string)) # ['l5python_'] print(re.findall("\spython\d\s", string)) # [' python2 '] ``` ### 普通字元 * 一般標記:以 [] 自訂範圍作配對 ```python= import re string = "dafuiwefjpepythonx3hellopythona_123e5" print(re.findall("\wpython[xyz]\w", string)) # ['epythonx3'] print(re.findall("\wpython[^xyz]\w", string)) # ['opythona_'] ``` * 範圍標記 * 以[x-y]表示特定連續範圍 * 範圍依照字元對應ASCII Code * x<y ,若 x>y 則會錯誤 * 排除字元;以'^'表示該範圍須排除 ### 邊界、限定符號 |符號|意義| | :--------: | :-------- | | ^ |配對字串開始位置| | $ |配串字串結束位置| | \b |配對字的邊界| ```python= import re string = "abcdwfijod_G2killSKTwTF_ajfioe_py" print(re.search("^abd", string)) #None print(re.search("abc", string)) #<re.Match object;span=(0,3), match='abc'> print(re.search("py$", string)) #<re.Match object;span=(31,33), match='py'> print(re.search("ay$", string)) #None ``` |符號|意義| | :--------: | :-------- | | * |配對0次、1次或多次前面字元| | ? |配對0次或1次前面的字元| | + |配對1次或多次前面的字元| ```python= import re string = "whenThesongplay_weheardyeeeea" print(re.search("ye*a", string)) #<re.Match object;span=(23,29), match='yeeeea'> print(re.search("ye?a", string)) #None print(re.search("hex?ard", string)) #<re.Match object;span=(18,23), match='heard'> print(re.search("ye+a", string)) #<re.Match object;span=(23,29), match='yeeeea'> print(re.search("hex+ard", string)) #None ``` ### 貪婪模式:".*" ```python= import re string = "giepgpython598fes_py" print(re.search("p.*y", string)) #<re.Match object;span=(3,20), match='pgpython598fes_py'> ``` ### 懶惰模式:".*?" ```python= import re string = "giepgpython598fes_py" print(re.search("p.*?y", string)) #<re.Match object;span=(3,7), match='pgpy'> ``` ### 配對次數 | 符號 | 意義 | | :--------: | :-------- | |{n}|前面字元剛好出現n次| |{n,}|前面字元至少出現n次| |{n,m}|前面字元至少出現n次,至多出現m次| | \| |選擇性配對| |( )|Capturing Group| ```python= import re string = "themonkey_pickabanana_itplaaaaayhard" print(re.search("la{2}", string)) #<re.Match object;span=(25,28), match='laa'> print(re.search("la{2,}", string)) #<re.Match object;span=(25,31), match='laaaaa'> print(re.search("la{2,4}", string)) #<re.Match object;span=(25,30), match='laaaa'> ``` ```python= import re string = "hguierjgngphp_sdfireg" print(re.search("python|php", string)) #<re.Match object;span=(10,13), match='php'> string = "therearebugbugbugbugbug_everywhere" print(re.search("(bug){1,}", string)) #<re.Match object;span=(8,23), match='bugbugbugbugbug'> string = "idsoadxyzffdspdo_adfj" print(re.search("(a|b)(c|d)\w{3}", string)) #<re.Match object;span=(4,9), match='adxyz'> ``` ### Flag |符號|意義| | :--------: | :-------- | |I|忽略大小寫| |M|多行配對| |S|讓 ' . ' 可以配對換行符號| ```python= import re string = "caqyqjkgqmoxlybPythoneaytlricbdg" print(re.search("python", string)) #None print(re.search("python", string, re.I)) #<re.Match object;span=(15,21), match='Python'> ``` ### 環顧 | 符號 | 意義 | 比對成功回傳值 | | :--------: | :-------- | :--------: | |(?=...)|右方要出現...|True| |(?!...)|右方不能出現...|False| |(?<=...)|左方要出現...|True| |(?<!...)|左方不能出現...|False| ## 實作 ### 爬蟲 * URL * Soure Code * Data #### 搜尋方法 * 聚焦爬蟲 * 廣度優先搜尋 * 深度優先搜尋 #### 常見代碼錯誤 | 常見錯誤碼 | 代號說明 | | :--------: | -------- | |2XX|成功狀態碼(Success),已成功接受客戶端請求| |4XX|客戶端錯誤(Client Error),客戶端請求出錯導致服務端無法正常完成請求| |400|客戶端請求訊息不正確| |401|客戶端請求訊息不被授權| |402|客戶端完成請求必須要有回應| |403|客戶端被禁止使用此資源| |404|(Not Found)伺服器無法找到請求的頁面或資源| |405|(Method Not Allowed)方法不允許,方法禁用| |406|客戶端不被接受| |5XX|服務端錯誤(Server Error),伺服器出錯未能成功處理服務端請求| #### HTML Tag ![](https://i.imgur.com/TDkWJMq.jpg) * open tag * \<ul> * \<a> * \<script> * close tag * \</ul> * \</a> * \</script> * 少數沒有close tag * \<img> * \<input> #### XPath(XML Path Language) 用來尋找XML某個節點的查詢語言,包含七種節點 1. element 2. attribute 3. text 4. namespace 5. document 6. comment 7. processing-instruction ### 人工智慧 [keras](https://keras.io/examples/vision/captcha_ocr/) [keras做CNN模型](https://notes.andywu.tw/2019/%E7%94%A8tensorflowkeras%E8%A8%93%E7%B7%B4%E8%BE%A8%E8%AD%98%E9%A9%97%E8%AD%89%E7%A2%BC%E7%9A%84cnn%E6%A8%A1%E5%9E%8B/) # 物件導向 * 類別class * 方法method * 物件object * "人"是一個類別,"劉昊然"是生成的物件 ## 類別宣告 ![](https://i.imgur.com/jedM7WE.png) ```python= class class_name(): def __init__(self, x, y): #一些初始化 def method(self, k): #... ``` ### self 代表這個類別本身,生成物件和呼叫方法時不需要寫進參數裡 ![](https://i.imgur.com/YYhYHBR.png) ## 物件生成 ```python= <物件名稱> = <該類別>(參數) ``` ### 使用方法和存取屬性 ```python= <物件名稱>.<方法名稱>(參數) <物件名稱>.<參數名稱> ``` ### Example ![](https://i.imgur.com/gLmKC8I.png) ```python= '''Example''' class Person(): name = "" age = 0 def __init__(self, name, age): #constructor建構子 #一旦設定,產生物件時就必須有參數 self.name = name self.age = age def set_Name(self, name): self.name = name def set_Age(self, age): self.age = age #產生類別 person = Person("Angel", 25) #person = Person() #TypeError: __init__() missing 2 required positional arguments: 'name' and 'age' print(person.name) # Angel print(person.age) # 25 #呼叫類別裡的方法 person.set_Name("Sombra") person.set_Age(19) print(person.name) # Sombra print(person.age) # 19 ``` ## 繼承Inheritance ![](https://i.imgur.com/TT4g1yF.png) ## 私有物件變數 ## Property ## 類別變數