--- image: https://i.imgur.com/PJKX0hj.jpg --- # Python Basic Notes ###### tags: `python` > [TOC] 最後修改時間: > [time=Mon, Jul 18, 2022 11:11 PM] :::warning :warning:**警告 :** 請實際跟著打打看,有疑惑馬上Google,別當伸手黨,自己查資料沒那麼困難。 看到沒看過的東西?Google「python+關鍵字』就好啦!請點點看以下連結。 1. [Python how to expand an array](https://letmegooglethat.com/?q=Python+how+to+expand+an+array) 2. [Python how to delete one element from list](https://letmegooglethat.com/?q=Python+how+to+delete+one+element+from+list) 3. [Python convert dict to json](https://letmegooglethat.com/?q=Python+convert+dict+to+json) 4. **Come on... Was that really so hard for you?** ![](https://i.imgur.com/PJKX0hj.jpg) **還有,基礎語法必須自己掌握,這裡提供的是一些重點跟感覺。** ~~當然,我也是菜鳥,如果哪裡搞錯,麻煩告訴我,我才剛認真學1個月。~~ 有錯誤歡迎留言,感謝。 ::: :::info :blue_book: **用法 :** ``` 某一行程式碼 # 表示印出的結果 某一行有input的 # >>表示請跟著輸入 ``` 或是程式碼內有詳細說明的註解,而下方有執行結果。 **注意,程式碼不要逐行看,請先看有呼叫、輸出的地方。** ::: :::success :pencil: **開始寫 :** 1. [onlinegdb.com](https://www.onlinegdb.com/online_python_compiler) 2. [repl.it](https://replit.com/languages/python3) 3. [Colaboratory](https://colab.research.google.com/notebooks/intro.ipynb?utm_source=scs-index) **請選擇上方的一個線上IDE立刻開始寫。** ::: :::danger :100: **題庫練習:** * [ITSA數學 I(Mathematics)](https://hackmd.io/@cheung4843/Sykbp_f9O) ::: --- ## 入門 ### 基礎 ```py= import decimal a=41 b=82 print('Hello!') # Hello print("1 + 1 =",1+1) # 1 + 1 = 2 print(type(a)) # <class 'int'> print(id(a)) # e.g. 10106368 print(float(6)) # 6.0 print(10/3) # 3.3333333333333335 print(10//3) # 3 print(int(10//3)) # 3 print(decimal.Decimal(10/3)) # 3.333333333333333481363069950020872056484222412109375 print(4==5) # False if(a*2==b and True or False or not(b==1)): print('right') # right ``` :::info :bulb: 筆記: 1. import 模組。 2. print()印出字串。 3. type()取得類別。 4. id()取得記憶體位置。 5. int()、float()負責轉型。 6. 分別'/'與'//'。 7. decimal.Decimal()取得更精確的浮點數。 8. 4==5、3!=4、1>2等都會得到一個布林值(True、False)。 9. 留意and、or、not的差別。 10. if(條件式),若成立就執行下一行的程式碼。 ::: ### 數字處理 ```python= import math from fractions import Fractions c=14 print(bin(c)) # 0b1110 print(hex(c)) # 0xe print(format(c,'b')) # 1110 print(format(c,'x')) # e print(c**2) # 196 print(math.pow(c,2)) # 196.0 print(complex(2,3)) # (2+3j) print(Fraction(1,41)) # 1/41 print(bin(11)) # 0b1011 print(bin(14)) # 0b1110 print(bin(11&10)) # 0b1010 print(11&10) # 10 print(40&1) # 0 print(41&1) # 1 print(bin(6)) # 0b110 print(bin(-6)) # -0b111 print(~6) # -7 print(bin(10)) # 0b1010 print(bin(14)) # 0b1110 print(bin(10^14)) # 0b0100 print(10^14) # 4 print(bin(4)) # 0b100 print(bin(4<<1)) #0b1000 print(4<<1) # 8 ``` :::info :bulb: 筆記: 1. 0b代表二進位數字;,0x代表16進位數字;那為何要放0呢?因為變數名稱不允許以數字為開頭,所以用0來告訴編譯器這是一個數字。 2. bin()轉二進位,hex()轉十六進位。 3. foramt(數字,進位制)差別在於前面的0b或0x顯示於否。 4. 注意'**'與pow函數的差異。 5. complex(實部,虛部) 6. fractions.Fraction(分子,分母) 7. 可以利用&運算來判斷偶奇數。 8. 二進位數字最高位數字為1表負數。例如11111001為-7 9. "<<"與">>"分別是位元左移或右移一格,即乘2或除2。 ::: ### 輸入 ```python= number1=input("please keyin number1:") # >> 4 number2=input("please keyin number2:") # >> 5 print("The sum is",number1+number2) # The sum is 45 print("The sum1 is",int(number1)+int(number2)) # The sum1 is 9 number3=int(input("please keyin number3:")) # >> 41 print("The sum2 is",int(number2)+number3) # The sum2 is 46 ``` :::info :bulb: 筆記: 1. 記得變數的型態。 2. input()輸入字串。 3. 變數若不轉型就相加,就是字串連結。 ::: ### 選擇結構 ```python= score=int(input()) # >> 76 if score>=90: print("excellent") elif(score>=60): print("pass") # pass else: print("gg") ``` :::info :bulb: 筆記: 1. 注意判斷式的先後順序。 ::: ### 重複結構 ```python= n=int(input("要求幾階層:")) # >> 5 ans=1 for count in range(1,n+1): ans*=count print("答案是",ans) # 120 sum=0 m=int(input("要從0累加到多少:")) # >> 100 for i in range(0,m+1): sum+=i print("總和為",sum) # 5050 cnt=1 tmp=2**10 while(cnt<=10): tmp=tmp>>1 cnt+=1 print(tmp) # 1 total=0 j=1 limit=int(input("停損點:")) # >> 100 while(2>1): total+=j if(total>=limit): print('當j={a}時,total大於等於{b}'.format(a=j, b=limit)) # 當j=14時,total大於等於100 break else: j=j+1 ``` :::info :bulb: 筆記: 1. 想想為什麼ans要賦值為1、還有為何range內的兩個參數要這麼放。 2. 如果要求任兩個數區間和,range該怎麼改呢? 3. while()括號內的條件成立,就會執行到不成立為止,小心無窮迴圈。 4. cnt+=1跟cnt=cnt+1是一樣意思的。 5. 注意print與format搭配的格式化輸出。 6. break語法可中斷迴圈。 ::: ### 函數(Function) ```python= def f(n): if(n==1): return 1 else: return n*f(n-1) x=int(input()) # >> 6 print(f(x)) # 720 def g(*number): return number print(g(1,2)) # (1, 2) print(g(1,3,4)) # (1, 3, 4) def mod(a, b): q = a // b r = a % b return q, r x, y = mod(30, 7) print(f'商數={x},餘數={y}') # 商數=4,餘數=2 ``` :::info :bulb: 筆記: 1. 分別階層的迴圈與遞迴寫法。 2. 留意不定個參數的寫法。 3. return 也可以傳出多個值,相同的,要以等量的變數去承接。 ::: ### 串列(List) ```python= What_i_learned=["python","C++","C","Java","Typescript"] idx=int(input()) # >> 0 print(What_i_learned[idx]) # python print(What_i_learned[1:]) # ['C++', 'C', 'Java', 'Typescript'] print(What_i_learned[:3]) # ['python', 'C++', 'C'] print(What_i_learned[1:3]) # ['C++', 'C'] print(What_i_learned[-1]) # Typescript print(What_i_learned[-2:]) # ['Java', 'Typescript'] print(What_i_learned[:-2]) # ['python', 'C++', 'C'] print(What_i_learned[-4:-2]) # ['C++', 'C'] print(What_i_learned[-2:-5]) # [] print(What_i_learned[:]) # ['python', 'C++', 'C', 'Java', 'Typescript'] print(What_i_learned) # ['python', 'C++', 'C', 'Java', 'Typescript'] print(What_i_learned[0:5:2]) # ['python', 'C', 'Typescript'] print(What_i_learned[::2]) # ['python', 'C', 'Typescript'] print(What_i_learned[::-1]) # ['Typescript', 'Java', 'C', 'C++', 'python'] print(What_i_learned[::-2]) # ['Typescript', 'C', 'python'] print(What_i_learned[-1:-5:-2]) # ['Typescript', 'C'] print(What_i_learned[::0]) # ValueError: slice step cannot be zero new_language=input() # >> kotlin What_i_learned.append(new_language) print(What_i_learned) # ['python', 'C++', 'C', 'Java', 'Typescript', 'kotlin'] number_1=[1,2,3,41,41,41,41] number_2=[42,43,44,45] print(number_1.count(41)) # 4 print(number_2.count(0)) # 0 number_1.extend(number_2) print(number_1) # [1, 2, 3, 41, 41, 41, 41, 42, 43, 44, 45] number_3=[46,47] print(len(number_1)) # 11 print(len(number_2)) # 4 number_2[len(number_2):]=number_3 print(number_2) # [42, 43, 44, 45, 46, 47] Name=list("Sean") print(Name) # ['S', 'e', 'a', 'n'] number_4=[1,2,4,0,41] print(max(number_4)) # 41 print(min(number_4)) # 0 del number_4[3] print(number_4) # [1, 2, 4, 41] number_4[3]=8 print(number_4) # [1, 2, 4, 8] String1=['p','y','t','h','o','n'] print(String1) # ['p', 'y', 't', 'h', 'o', 'n'] String1[1:]=list('qrsyz') print(String1) # ['p', 'q', 'r', 'a', 'b', 'c'] String1[3:6]=['s','y','z'] print(String1) # ['p', 'q', 'r', 's', 'y', 'z'] print('p' in String1) # True arr_1=['I','Love'] arr_2=['You','So much'] print(arr_1+arr_2) # ['I', 'Love', 'You', 'So much'] arr_3=[1,2,3] print(arr_3*3) # [1, 2, 3, 1, 2, 3, 1, 2, 3] ``` :::info :bulb: 筆記: 1. 從左到右由0開始編號,從右到左從-1開始。 2. What_i_learned[idx] 直接取出該索引對應的內容。 3. What_i_learned[起點(包含):終點(不包含)]。 4. What_i_learned[起點(包含):終點(不包含):X],若X為正數,表示一次向右跳X;反之X為負數,一次向左跳X。 5. 不允許一次跳0格。 6. append()新增元素。 7. count()計算該元素出現幾次。 8. extend()延伸(合併)。 9. len()取得長度。 10. len()還可以連結串列。 11. list()可將字串轉成串列。 12. max()、min()分別找出最大與最小值。 13. del用來刪除元素。 14. number_4[3]=8,將41取代成8。 15. 活用list()來插入與取代原串列。 16. 活用[起點:終點(不包含)]來取代範圍內的內容。 17. X in list 檢查X是否在list內。 18. 也可以用+號連接串列。 19. 可用*號將串列自我複製。 20. List is mutable ::: ### 序對(Tuple) ```python= data_structures=("array","linked_list","queue",) print(data_structures) # ('array', 'linked_list', 'queue') data_structures[0]="hashMap" print(data_structures) # TypeError: 'tuple' object does not support item assignment ``` :::info :bulb: 筆記: 1. 序對是用(),串列是用[]。 2. 序對不可更改,而串列可以。 3. 思考為何'queue'後多一個逗號,仍能執行。 ::: ```python= a=3*(4+5) print(a) # 27 b=3*(4+5,) print(b) # (9, 9, 9) data_structures=("array","linked_list","queue","deck") print(data_structures[1:3]) # ('linked_list', 'queue') print(data_structures[0:3:2]) # ('array', 'queue') print(data_structures[::-1]) # ('deck', 'queue', 'linked_list', 'array') coding=("IDE","interpreter",("python","Julia"),"debug",("bfs","dfs")) print(coding) # ('IDE', 'interpreter', ('python', 'Julia'), 'debug', ('bfs', 'dfs')) print(coding[2]) # ('python', 'Julia') num1=((1,2),(2,4),(1,2),(4,8),1) print(num1.count((1,2))) # 2 print(num1.count(1)) # 1 ``` :::info :bulb: 筆記: 1. a是數字,b是序對。 2. 序列與串列的取法一樣。 3. 序對裡可以再包含序對。 4. 思考為何最後一行的輸出為何不是3。 ::: ### 字典(Dictionary) ```python= ScoreTable={"Sean":100,"Mary":76,"Candy":86,"Kelly":54,"Tony":94} print(ScoreTable) # {'Kelly': 54, 'Candy': 86, 'Sean': 100, 'Mary': 76, 'Tony': 94} print(ScoreTable["Sean"]) # 100 ScoreTable["Sophia"]=84 print(ScoreTable) # {'Sean': 100, 'Mary': 76, 'Sophia': 84, 'Kelly': 54, 'Tony': 94, 'Candy': 86} ScoreTable["Kelly"]=60 print(ScoreTable["Kelly"]) # 60 del ScoreTable["Mary"] print("Mary" in ScoreTable) # False copyTable=ScoreTable.copy() print(copyTable) # {'Candy': 86, 'Kelly': 60, 'Sophia': 84, 'Sean': 100, 'Tony': 94} ScoreTable.clear() print(ScoreTable) # {} ``` :::info :bulb: 筆記: 1. dict[key]=value 2. copy()用來複製。 3. clear()用來清空。 4. 相對於list來說,dict可以用字串來取值。 ::: ### 集合(Set) ```python= books={"math","cs"} print(books) # {'cs', 'math'} or {'math', 'cs'} print(books[0:2]) # TypeError: 'set' object is not subscriptable ``` :::info :bulb: 筆記: 1. 每次輸出set的結果可能不一樣,因為是無序的。 2. 因為集合是無序的,不能再取出某範圍中的內容。 ::: ```python= MyLove={"Freedom","Happiness","Family","procrastination"} print(len(MyLove)) # 4 MyLove.add("Girlfriend") print(len(MyLove)) # 5 MyLove.add("Freedom") print(len(MyLove)) # 5 MyLove.remove("procrastination") print(len(MyLove)) # 4 ``` :::info :bulb: 筆記: 1. add()用來增加新元素。 2. 已有的元素加進去集合,並不會有影響。 3. remove()用來刪除。 ::: ### 類別(Class) ```python= class Robot(): __code=123 def __init__(self,power): self.power=power def say_Hello(self): print("Hello") def show_code(self): print(self.__code) class Robot_A(Robot): def tell_code(self): self.show_code() def print_code(self): super().show_code() def say_code(self): print(self.__code) Sean = Robot(1000) print(Sean.power) # 1000 Sean.show_code() # 123 Sean.say_Hello() # Hello print("---------") Sophia = Robot_A(500) print(Sophia.power) # 500 Sophia.say_Hello() # Hello Sophia.tell_code() # 123 Sophia.show_code() # 123 Sophia.print_code # 123 Sophia.say_code() # AttributeError: 'Robot_A' object has no attribute '_Robot_A__code' ``` :::info :bulb: 筆記: 1. self用來表示類別本身。 2. 雙底線init雙底線()用來初始化。 3. Robot_A(Robot),Robot_A繼承了Robot。 4. 子類別通過繼承調用父類別的原生函式。 5. 可以覆寫父類別的函式,或是新增自己的函式。 6. 雙底線在前頭的變數除了父類別的原生函式、子類別調用其繼承的函式、子類別透過super()呼叫能取得之外,其他子類別的原生函式無法直接取得。 ::: ```python= class animals(): def __init__(self,hp): self.hp=hp self.damage=10 def sleep(self): print("Zzzz..") self.hp+=10 def what_we_are(slef): print("animals") class Cat(animals): def meow(self): print("MEOW!") self.damage+=5 def info(self): print("hp={a},damage={b}".format(a=self.hp,b=self.damage)) def Who_Am_I(self): print("Cat~") class kitten(Cat): def __int__(self,hp): self.hp=hp self.damage=5 def meow(self): print("meow~meow~meow~") self.damage+=3 def play(self): self.hp+=3 print("=^∇^*=") def Who_Am_I(self): super().what_we_are() MyCat=Cat(100) MyCat.info() # hp=100,damage=10 MyCat.meow() # MEOW! MyCat.info() # hp=100,damage=15 MyCat.sleep() # Zzzz.. MyCat.info() # hp=110,damage=15 MyCat.Who_Am_I() # Cat~ print("----------") # ---------- kelly=kitten(50) kelly.info() # hp=50,damage=10 kelly.meow() # meow~meow~meow~ kelly.info() # hp=50,damage=13 kelly.play() # =^∇^*= kelly.info() # hp=53,damage=13 kelly.what_we_are() # animals kelly.Who_Am_I() # animals ``` :::info :bulb: 筆記: 1. 父類別->子類別->孫類別 2. 繼承的類別可以調用其繼承的所有類別方法。 3. 類別會優先執行最近所覆寫的函式。 4. super(),可以調用到祖類別的函式。 5. 有點亂對不對?你試著自己玩玩看。 ::: ### 字串(String) ```python= import re str_a='I am Sean' str_b="Hi~" print(str_b) # Hi~ print(str_a[5:8]) # Sea print(str(2352)+str(123)) # 2352123 str_U="ABCD" str_l="efgh" print(str_U.lower()) # abcd print(str_l.upper()) # EFGH str_c="Sean" print(re.match("Sea",str_c)) # <_sre.SRE_Match object; span=(0, 3), match='Sea'> print(re.match(str_c,"Sea")) # None ``` :::info :bulb: 筆記: 1. 字串可以想成裝著字元的串列,但又不能直接修改其中的元素。 2. str()轉字串。 3. lower()轉小寫;upper()轉大寫。 4. re.match(a,b)留意a與b的關係。 ::: ### 例外/錯誤處理(try-catch) ```python= a=int(input()) b=0 try: print(a/b) except: print("ZeroDivisionError: division by zero") # ZeroDivisionError: division by zero finally: print("finished") # finished ``` :::info :bulb: 筆記: 1. try:,你要監控的程式碼區段。 2. except:,例外的處理。 3. finally:,不管如何最後一定會執行的。 ::: --- ## 進階 ### Base ```python= print("123",end='4\n') # 1234 print("567",end='89') # 56789 print("\n987654") # 987654 a,b,c=1,3,5 d=7;e=9;f=11 print(a,b,c) # 1 3 5 print(d,e,f) # 7 9 11 print(not 0,not 1,not 2,not 3,bool(4),False+1) # True False False False True 1 print(123e4) # 1230000.0 print(456e-2) # 4.56 ``` :::info :bulb: 筆記: 1. end='x',表示將輸出的結尾設為'x' 2. 留意逗號跟分號何時使用。 3. 非0的數字都可當為True。 4. e用來表示科學符號中10的冪次。 ::: ### Loop ```python= g=16 while g<34: print(g,"<=34",end=", ") # 16 <=34, 22 <=34, 28 <=34, g+=6 else: print("\n{i}>={j},done!".format(i=g,j=34)) # 34>=34,done! for x in range(1,15,5): print(x,end=' ') # 1 6 11 print('\n-----') # ----- for y in range(-1,-12,-4): print(y,end=' ') # -1 -5 -9 print('\n-----') # ----- u,v=3,3 for i in range(1,u): for j in range(1,v): print("%d*%d=%d" %(i,j,i*j),end=',') # 1*1=1,1*2=2,2*1=2,2*2=4, print('\n-----') # ----- arr=[0]*5 for i in range(0,len(arr)): arr[i]=i+1 for i in range(0,len(arr)): print(arr[i],end=' ') # 1 2 3 4 5 print('\n-----') # ----- for val in arr: print(val+1,end=' ') # 2 3 4 5 6 print('\n-----') # ----- numberList=[0,0.5,1,1.5,2] n=[int(x) for x in numberList] print(n) # [0, 0, 1, 1, 2] m=[float(x) for x in numberList] print(m) # [0.0, 0.5, 1.0, 1.5, 2.0] ``` :::info :bulb: 筆記: 1. while的else會在不符合條件時執行。 2. range(起點,終點(不包含),前進或後退的格數) 3. 雙層迴圈會執行$u*v$次。 4. 可以利用foreach的方式逐步走訪串列。 5. 利用[int(x) in for x in list]取得全部元素型態都為int的串列。 ::: ### global ```python= money=100 def bag(): global money print(money) # 100 money=200 print(money) # 200 bag() ``` :::info :bulb: 筆記: 1. 第1行的money是全域變數。 2. 第7行的money是區域變數。 3. 試試看把第4行拿掉看看。 ::: ### Lambda ```python= fun_a=lambda x:x+41 fun_b=lambda x,y:x*y print(fun_a(41)) # 82 print(fun_b(4,1)) # 4 print((lambda x,y:x-y)(4,1)) # 3 title="python is beautiful." (lambda title:print(title))(title) # python is beautiful. (lambda:print("Python is the best!"))() # Python is the best! abs = lambda x: x if x >=0 else -x print(abs(-7)) # 7 fun = lambda x: x ** 3 if 2 <= x <= 6 else x ** 2 print(fun(4), fun(12)) # 64 144 ``` :::info :bulb: 筆記: 1. lambda就只是個運算式,只能一行。 ::: ### Curry ```python= def f1(a): def f2(b): return a+b return f2 print(f1(40)(1)) # 41 ``` :::info :bulb: 筆記: 1. Curry將兩個函式結合在一起。 ::: ### Parameter ```python= import math def f(*x,arr=[]): arr.append(x) print(arr) f(2,4,6,8,10) # [(2, 4, 6, 8, 10)] b=[2, 4, 6, 8, 10] print(b) # [2, 4, 6, 8, 10] def g(*y,arr=None): if(arr is None): arr=[] arr.append(y) print(arr) g(1,3,5,7,9) # [(1, 3, 5, 7, 9)] def h(u,v): return u-math.fabs(u*v) print(h(3,-4)) # -9 print(h(v=-4,u=3)) # -9 def p(**x): print(x) p(a=1,b=4,c=7) # {'a': 1, 'b': 4, 'c': 7} def z(a,b,c,d,e): return a+b+c+d+e print(2,4,*range(6,12,2)) # 2 4 6 8 10 print(z(2,4,*range(6,12,2))) # 30 print(z(*range(5))) # 10 ``` :::info :bulb: 筆記: 1. def 函式(參數1, 參數2=預設值...),其中沒有預設值的參數稱為位置(position),必須放在前面,而有預設值的參數稱為關鍵字參數或是指名參數則必須放在後面,要注意的是,指名參數可以用「參數=值」的方式傳入函式而取代原本的預設值。 2. math.fabs()取絕對值。 3. 兩個星字號代表參數類別是dict。 4. 用一個星字號來來拆解迭代物件。 ::: ### List、Iterator ```python= arr=[2,4,6,8,9,10] if 9 in arr: print("ohoh") # ohoh if 12 not in arr: arr.append(12) print(arr) it=iter(arr) for val in range(0,len(arr)): print(next(it),end=' ') # 2 4 6 8 9 10 12 print("\n-----") oddList=[1,{2,3,4},[5,6,7],(8,9,10),{'a':11,'b':12,'c':13}] print(oddList) # [1, {2, 3, 4}, [5, 6, 7], (8, 9, 10), {'a': 11, 'b': 12, 'c': 13 del arr[0:len(arr):2] print(arr) # [4, 8, 10] arr.remove(max(arr)) print(arr) # [4, 8] ``` :::info :bulb: 筆記: 1. 利用迭代器與next取得串列的內容。 2. 串列內可以放入不同的類別。 3. del和remove()可以刪除一個元素,而del也可使用切片語法(slicing)刪除多個。 ::: ### Tuple ```python= str1="I Love you, python." print(tuple(str1)) # ('I', ' ', 'L', 'o', 'v', 'e', ' ', 'y', 'o', 'u', ',', ' ', 'p', 'y', 't', 'h', 'o', 'n', '.') num1=[1,2,3,4,5] num2=(6,7,8,9,10,) print(tuple(num1)+num2) # (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) print(tuple(num1)*2) # (1, 2, 3, 4, 5, 1, 2, 3, 4, 5) num3=(2,4,2,6,8,4) print(num3.index(4)) # 1 for x in num3: print(x,end=' ') # 2 4 2 6 8 4 print("\n------") it=iter(num3) for x in range(0,len(num3)): print(next(it)+1,end=' ') # 3 5 3 7 9 5 print("\n------") str2="python" a,b,c,d,e,f=str2 print(a,b,c,d,e,f) # p y t h o n ``` :::info :bulb: 筆記: 1. tuple()可將字串、串列轉成序對。 2. 利用index(),取得元素第一次出現的索引。 3. 利用迭代器與next取得序對的內容。 ::: ### Dictionary ```python= mydict=dict([["Sean",89],("Tom",76)]) print(mydict) # {'Tom': 76, 'Sean': 89} or {'Sean': 89, 'Tom': 76} list1=['a','b','c','d'] list2=[1,2,3,4,5] list3=list(zip(list1,list2)) print(list3) # [('a', 1), ('b', 2), ('c', 3), ('d', 4)] print(dict(list3)) # e.g. {'d': 4, 'c': 3, 'b': 2, 'a': 1} newdict={"weapon":("sword","Rocket launcher"),"damage":[100,9999]} print(newdict) # {'weapon': ('sword', 'Rocket launcher'), 'damage': [100, 9999]} capitals = {'臺灣':'臺北', '日本':'東京', '越南':'河內', '中國':'北京', '美國':'華盛頓'} del capitals['中國'] capitals.pop('美國') print(capitals) # {'臺灣': '臺北', '日本': '東京', '越南': '河內'} ``` :::info :bulb: 筆記: 1. dict()可將串列或序對轉成字典。 2. zip()可將兩個序列或序對「縫起來」。 3. 字典內可放入不同類別的值。 4. 可利用del與dict.pop(key)來刪除字典內的元素。 ::: ### Set ```python= LM_cps=set(["社長","YJK0805","長頸鹿",("翻譯年糕","紅危")]) print(LM_cps) # e.g. {('翻譯年糕', '紅危'), 'YJK0805', '長頸鹿', '社長'} num1={1,2,3,4,5} num2={3,4,5,6,7} print(num1.union(num2)) # {1, 2, 3, 4, 5, 6, 7} print(num1.intersection(num2)) # {3, 4, 5} print(num1.difference(num2)) # {1, 2} print(num2.difference(num1)) # {6, 7} print(num1.symmetric_difference(num2)) # {1, 2, 6, 7} print(num2.symmetric_difference(num1)) # {1, 2, 6, 7} ``` :::info :bulb: 筆記: 1. set()可將串列或序對轉成集合。 2. union()取聯集。 3. intersection()取交集。 4. difference()取差集,有順序性。 5. symmetric_difference()取相對差集,各取彼此的差集再取聯集。 ::: --- ## 補充 ### enumerate() ```python= d = [1,2,3,4,3,4,4] print(list(enumerate(d))) for index, item in enumerate(d): print(index, item) ``` ![](https://i.imgur.com/UOYhOXT.png) ### zip() ```python= name_list = ['長頸鹿', '園長', '冥能師', '紅危猴子', '惠文王'] power_list = [85, 99, 87, 78, 100] print(list(zip(name_list, power_list))) for name, power in zip(name_list, power_list): print(name, power) ``` ![](https://i.imgur.com/oZpAU11.png) ### dict.items() ```python= club_dict = {'長頸鹿':3, '園長':1, '冥能師':4, '紅危猴子':2, '惠文王':0, '鮪魚':5} print(list(club_dict.items())) for name, id in club_dict.items(): print(name, id) ``` ![](https://i.imgur.com/Pwd1Ihk.png) ### function() vs. container.method() ```python= pin = [1533, 4843, 1111, 5341, 4844] print(sorted(pin)) # [1111, 1533, 4843, 4844, 5341] print(pin) # [1533, 4843, 1111, 5341, 4844] pin.sort() print(pin) # [1111, 1533, 4843, 4844, 5341] ``` :::info :bulb: 筆記: 1. sorted()回傳一個排序後的新串列,但不改變原串列的內容。 2. list.sort()將原序列進行排序,並直接改變內容。 3. 同理,reverse()與list.reverse()也是,只不過reverse()不會直接傳回list,需要使用list()轉換。 ::: ### format() vs. f-string ```python= fruits = [['apple', 'red'], ['watermelon', 'green'], ['banana', 'yellow']] for name, color in fruits: print('{} is {}?'.format(name, color)) print(f'{name} is {color}.') ``` ![](https://i.imgur.com/AAmRgMo.png) ### str.split() vs. re.split() ```python= import re sentence_a = 'I love my new life' print(sentence_a.split()) # ['I', 'love', 'my', 'new', 'life'] sentence_b = 'well, good for you' print(sentence_b.split(',')) # ['well', ' good for you'] sentence_c = 'umm...well... you have made yourself a lot different' list_c = sentence_c.split('...', 1) print(list_c) # ['umm', 'well... you have made yourself a lot different'] s = 'this.is,not,a.normal,string' print(re.split('[.,]', s)) # ['this', 'is', 'not', 'a', 'normal', 'string'] ``` :::info :bulb: 筆記: 1. str.split(分割字元, 分割次數),且預設字元是空白,若沒設定切割次數,則是將完整句子切割。 2. re.split('[分割符號]', 字串),在中括號中可以放不只一種分割符號,但得連在一起。 ::: ### map() ```python= a = [-1, -2, 5, -4] b = [] for val in a: b.append(abs(val)) print(b) # [1, 2, 5, 4] c = list(map(abs, a)) print(c) # [1, 2, 5, 4] strlist = ['THIS', 'IS', 'COOL.'] d = list(map(str.lower, strlist)) print(d) # ['this', 'is', 'cool.'] ``` :::info :bulb: 筆記: 1. map(函式名稱, 容器),只傳入函式本身,因為若加上()就是呼叫函式了。 2. 記得使用list()將map()處理後產生的map物件轉換成list。 3. map()此類可以將其他函式當成參數傳入的函式,可稱為高階函式(higher-order functions) ::: ### filter() ```python= a = ['123', 'heyhey', '456', '789', 'hoho'] print(list(filter(str.isdigit, a))) # ['123', '456', '789'] print(list(filter(lambda s: len(s) > 3, a))) # ['heyhey', 'hoho'] ``` :::info :bulb: 筆記: 1. filter(函式, 容器)與map()使用方法類似,但傳入函式只能是布林函式。 2. 「lambda s: len(s) > 3」與「lambda s: True if len(s) > 3 else False」意思相同,因為len(3) > 3本身就會回傳一個布林值。 ::: ### sorted() ``` python= a = ['1234', 'heyhey!!', '45', '789', 'hoho~'] print(sorted(a, key=len)) # 按照長度來排列,由小到大 print(sorted(a, key=len, reverse=True)) # 由大到小 b = [1, 6, 0, 4, 6, 7] b.sort(reverse=True) # 由大到小排列 print(b) print('-----') c = [[1, 2, 4], [4, 5, 9], [8, 6, 3], [3, 7, 6]] print(sorted(c)) # 因無指定排列根據,由第1個子元素由小到大排列 print(sorted(c, key=lambda x:x[1])) # 由第2個子元素由小到大排列 print(sorted(c, key=lambda x:x[2], reverse=True)) # 由第3個子元素由大到小排列 ``` ![](https://i.imgur.com/BxZ2wAW.png) ### list comprehension ```python= a = [-1, -8, -6, 3] print([abs(val) for val in a]) # [1, 8, 6, 3] print(list(map(abs, a))) # [1, 8, 6, 3] print([v ** 2 for v in a]) # [1, 64, 36, 9] print([str(x) for x in a]) # ['-1', '-8', '-6', '3'] print([x for x in a if x < 0]) # [-1, -8, -6] print(list(filter(lambda x: x<0, a))) # [-1, -8, -6] b = [1, 4, -2, 9] print([x + y for x, y in zip(a, b) if x + y >= 0]) # [0, 12] print([[x, y] for x, y in zip(a, b)]) # [[-1, 1], [-8, 4], [-6, -2], [3, 9]] c = [1, 2, 3] d = ['X', 'Y'] e = [] for x in c: for y in d: e.append([x, y]) print(e) # [[1, 'X'], [1, 'Y'], [2, 'X'], [2, 'Y'], [3, 'X'], [3, 'Y']] print([[x, y] for x in c for y in d]) # [[1, 'X'], [1, 'Y'], [2, 'X'], [2, 'Y'], [3, 'X'], [3, 'Y']] ``` :::info :bulb: 筆記: 1. [運算式 for 變數 in 容器 if 條件]就可以做到與map()或filter()相同的功能。 2. 第22行的程式碼可以這麼想:[x, y] for x in c 是個運算式E,那麼就可以表示為E for y in d。 ::: ### defaultdict ```python= from collections import defaultdict fruits = ['apple', 'banana', 'apple', 'watermelon', 'banana', 'mango', 'watermelon'] d = defaultdict(lambda:0) for fruit in fruits: d[fruit] += 1 print(d) # defaultdict(<class 'int'>, {'apple': 2, 'banana': 2, 'watermelon': 2, 'mango': 1}) prices = [['apple', 60], ['watermelon', 150], ['banana', 78], ['apple', 70], ['banana', 54]] e = defaultdict(list) for name, price in prices: e[name].append(price) for name, price in e.items(): print('key = {}, value = {}'.format(name, price),end=' || ') # key = apple, value = [60, 70] || key = watermelon, value = [150] || key = banana, value = [78, 54] || ``` :::info :bulb: 筆記: 1. defaultdict(函式, dict),若用不存在的鍵取值,它會用函式的傳回值作為預設值,也就避免原本的dict使用不存在的鍵取值會發生錯誤的狀況與減少檢查、初始化的時間。 2. 第4行可以改成 d = defaultdict(int) ::: ### Counter ```python= from collections import Counter fruits = ['apple', 'banana', 'apple', 'watermelon', 'banana', 'mango', 'watermelon'] c = Counter(fruits) print(c) # Counter({'apple': 2, 'banana': 2, 'watermelon': 2, 'mango': 1}) for fruit, times in c.items(): print(fruit, times, end='||') # apple 2||banana 2||watermelon 2||mango 1|| print('\n-----') print(c.most_common(1)) # [('apple', 2)] print(c.most_common(2)) # [('apple', 2), ('banana', 2)] ``` :::info :bulb: 筆記: 1. Counter也是一種特殊的dict,可以快速統計資料的出現次數。 2. Counter.most_common(X),輸出前X個出現最多次的資料。 ::: --- ## 有趣模組 ### turtle ```python= import turtle import time pen1 = turtle.Pen() pen2 = turtle.Pen() pen3 = turtle.Pen() colors = ['Green', 'Yellow', 'Blue', 'Red'] pen2.begin_fill() # 預備填色 pen3.begin_fill() pen3.penup() # 不畫出 pen3.setx(200) pen3.color('Red') # 設定顏色 for i in range(4): pen1.color(colors[i]) # 換顏色 pen1.forward(200) # 前進200畫素 if i < 2: pen3.pendown() # 畫出 pen2.circle(200, 90) # 畫1/4圓 pen2.left(90) # 逆時針90度 pen3.circle(200, -90) pen3.right(90) # 順時針90度 else: pen2.end_fill() # 填色 pen3.end_fill() pen1.left(90) time.sleep(5) # 停留5秒 ``` ![](https://i.imgur.com/yTHArzW.png) ### tkinter ```python= from tkinter import * import random rv = 200 c = 0 def again(): global c r1 = random.randint(300, 4 * rv) r2 = random.randint(200, 4 * rv) test2 = Tk() test2.title('中獎通知!') test2.geometry('400x300') test2.geometry('+{}+{}'.format(r1, r2)) c = c + 1 test2.configure(background=colors[c % 6]) label2 = Label(test2, text='您是第87000位造訪者!', width=15, height=2) label2.pack() button2 = Button(test2, text='關閉', command=again) button2.pack() r1 = random.randint(100, 4 * rv) r2 = random.randint(200, 3 * rv) test2 = Tk() test2.title('中獎通知!') test2.geometry('400x300') test2.geometry('+{}+{}'.format(r1, r2)) c = c + 1 test2.configure(background=colors[c % 6]) label2 = Label(test2, text='您是第87000位造訪者!', width=15, height=2) label2.pack() button2 = Button(test2, text='關閉', command=again) button2.pack() mainloop() colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] test = Tk() test.title('中獎通知!') test.geometry('400x300') test.configure(background=colors[c]) label1 = Label(test, text='您是第87000位造訪者!', width=15, height=2) label1.pack() button = Button(test, text='關閉', command=again) button.pack() mainloop() ``` ![](https://i.imgur.com/VvTbq8y.png) ### socket ```python= import socket def get_ip(website_name): print(socket.gethostbyname(website_name)) website = 'www.yahoo.com.tw' get_ip(website) # 124.108.115.100 ``` ![](https://i.imgur.com/ohsL7Wb.png) ## 最後 ### 建議 :::success :accept: **可以怎麼做 :** 1. 碰到Error或Exception,請不要著急,請看清楚錯誤名稱、原因,並查看哪行導致的,通常console都會有寫。 2. 寫程式遇到Error或Exception是很正常的事情,多善用try-catch。 ::: ### 提醒 :::warning :scroll: **該留意什麼 :** 1. 這些只是非常基本的語法和一些原始型別、資料結構的應用。 2. 實際上距離能解決「真正的」程式題目,仍需一大步。 3. 這裡只是帶個頭,實際上的學習仍然需要你自己在浩瀚無際的Google上探索。 4. 學習程式沒有捷徑,就是多打、多刷題、多Google。 5. 不要叫別人幫你Debug,我們不是通靈師,誰知道你的程式是寫什麼意思的。 6. 不要開口就當伸手黨,請自己做好功課再發問。 7. 可以的話,從C語言開始學起。 8. 多討論。 9. 參考[「假心得真建議」](https://hackmd.io/@cheung4843/HkDbGGqFd)。 10. 可以加入資訊社。 ::: > [time=Tue, Jun 29, 2021 8:25 PM]