#!/usr/bin/env python # coding: utf-8 # # 前情提要 # # # * 認識 Python # * 基本運算 # - 加減乘除 # - 取餘數 # - 指數 # - 複數 # - 除法,無條件捨去到個位數 (//) # - 絕對值 (abs) # - 四捨五入 (round) # * 型別 # - 基本型別 # + int # + float # + str # * `"` # * `'` # * `"""` # * `'''` # * `\` escape # + tuple # + list # + dict # + set # * `|` # * `&` # * `^` # * 輔助工具 # - dir # - help # - type # * 賦值 (Assign) # * 真偽值 # - True/False # - `>` `>=` `<` `<=` `==` `!=` `in` # - and/or/not # - is # - 各種 empty 狀況 # + 0, 1 # + "", "abc" # + (,), (1, 2) # + [], [1, 2] # + set(), {1, 2} # * 流程控制 (注意冒號和縮排) # - if ... elif ... else # - for ... in ... # - break # - continue # - while ... else ... # * 更多字串操作 # - format string # - 字串串接 # - slice : `start:stop[:step]` # * function # - def # - return # - arguments # + defaults # - function call # * Slice # - slice(start, stop[, step]) # - a[0], a[-1], a[1:99:3], a[-1:-11:-2], a[::-1] (不打的話就自動帶入頭尾), range(-1, -11, -2) # # 練習 # # (Home -> House Password) # # ![House Password](images/House-Password.png) # # (Home -> Xs and Os Referee) # # ![Xs and Os Referee](images/Xs and Os Referee.png) # # List # # ## List Methods # # * list.append # * list.reverse # * list.sort # * list.remove # * list.pop # * list.index # * list.insert # * list.count # In[1]: data = [1, 2, 3] data.append(4) # 加在最後面 print(data) data.reverse() # 反轉 print(data) data.append(42) # 加在最後面 print(data) data.sort() # 排序 (小到大) print(data) # In[2]: data = [1, 2, 3, 3, 2, 1] data.remove(1) # 去除第一個碰到的 1 print(data) # In[3]: data = ['a', 'b', 'c', 'd'] data.pop(0) # 去除第 0 項 print(data) # In[4]: data = ['a', 'b', 'c', 'd'] print(data.index('c')) # 找到位置 # In[5]: data = ['a', 'b', 'c', 'd'] data.insert(1, 'z') # 在 index 1 放入 'z' print(data) # In[6]: data = [1, 2, 3, 1, 4, 1, 5] print(data.count(1)) # 計算 1 出現的次數 # ## List Comprehension # # 更方便地建立 list # In[7]: [i*2 for i in (1, 2, 3)] # 依序從 (1, 2, 3) 裡拿資料出來,乘上 2 後放入 list # In[8]: result = [i for i in range(20) if i % 2 == 0] ''' result = [] for i in range(20): if i % 2 == 0: result.append(i) ''' print(result) # In[9]: result = [(i, i**2) for i in range(10)] print(result) # In[10]: result = [i if i % 3 == 0 else 1 for i in range(10)] ''' result = [] for i in range(10): if i % 3 == 0: result.append(i) else: result.append(1) ''' print(result) # # More String Operations # # 假設現在我們有字串 A 跟 B, # 內容分別為 "test" 和 "This is a test."。 # In[11]: A, B = "test", "This is a test." # ## A 是否是 B 的子字串 # In[12]: A in B # ## 把 B 用空格切割 # In[13]: B.split() # ## B 是以 "This" 開頭的? # In[14]: B.startswith("This") # ## 找到子字串的位置 # In[15]: B.find("test") # ## 字串重複 # In[16]: A * 3 # ## 字串連接 # In[17]: A + B # ## 字串用特定分隔符號連接 # In[18]: ' | '.join([A, B]) # In[19]: ' ~~~ '.join(['a', 'b', 'c', 'd']) # # Regular Expressions # # 玩點小遊戲 ~ # # * [Regex Crossword](https://regexcrossword.com/) # # ![Regex Crossword](images/regex-crossword.png) # ![Regex Puzzle](images/regex-puzzle-1.png) # # ---- # # * [PyRegex](http://www.pyregex.com/) # # ![PyRegex](images/pyregex.png) # # (我們直接看上面那張 Cheat Sheet 吧 ~) # # Import # # 利用現有的工具做事情 # # * [The Python Standard Library](https://docs.python.org/3/library/) # * [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) # In[20]: import getpass # 使用 Python 內建的 module password = getpass.getpass() # 輸入密碼 username = getpass.getuser() # 取得使用者名稱 # In[21]: from getpass import getpass, getuser # 指定使用 module 內的某些 function password = getpass() username = getuser() # In[22]: import getpass as g # 這邊把 "getpass" 這個 module 取名成 "g" (名字是隨便取的,正式專案不要亂命名) password = g.getpass() username = g.getuser() # # 自己寫 Module # # 我們一般寫的 Python 檔案就直接是 module,可以拿來 import。 # # 另外可以把多個 module 放在同一個資料夾,並且在資料夾內放入 `__init__.py` 就可以把整個資料夾變成 package 來使用。 # # ``` # . # └── mypackage #    ├── mymodule1 # └── mymodule2 # # ``` # In[23]: import re result = re.match('([0-9]{2})-([0-9]{7})', '03-0123456') print('.group() : {}'.format(result.group())) print('.group(0) : {}'.format(result.group(0))) # 整個 match 到的字串 print('.group(1) : {}'.format(result.group(1))) # match 到的第一個子 group print('.group(2) : {}'.format(result.group(2))) # match 到的第二個子 group print('.group(1, 2) : {}'.format(result.group(1, 2))) # match 到的第一和二個子 group print('.groups() : {}'.format(result.groups())) # match 到的所有子 group # In[24]: result = re.match('(?P[0-9]{2})-(?P[0-9]{7})', '03-0123456') print(result.groupdict()) # # Unpack # # 拆解 & 打包 # # * `*` : list # * `**` : dictionary # In[25]: a = (1, 2, 3) print(a) # In[26]: a, b, c = (1, 2, 3) print(a, b, c) # In[27]: a, *b = (1, 2, 3) # 把 tuple unpack,其中一部份 pack 給b print(a, b) # In[28]: a, *b, c = (1, 2, 3, 4) # 把 tuple unpack,其中一部份 pack 給b print(a, b, c) # In[29]: a, *b, c = (1, 2) print(a, b, c) # In[30]: for a, *b in [(1, 2, 3), ('a', 'b', 'c', 'd')]: # 在 for loop 裡使用 unpack print(a, b) # In[31]: def f(a, b, c): print(a, b, c) data = (1, 2, 3) f(*data) # unpack data, 等同於 f(1, 2, 3) # In[32]: def f(a=1, b=2, c=3, d=4): print(a, b, c, d) data = {'b': 42, 'd': 12} f(**data) # unpack data, 等同於 f(b=42, d=12) # In[33]: data = (1, 2, 3) print(*data) print(*data, 4, 5) # 這行在 Python 3.5 開始支援 # In[34]: a, b, *c = range(5) print(a, b, c) *a, b, c = a, b, *c # 這行在 Python 3.5 開始支援 print(a, b, c) # In[35]: a = [1, 2, 1, 3, 1, 4] b = {*a} # 這行在 Python 3.5 開始支援,等同於 set(a) print(b) # In[36]: def f(number, *args, **kwargs): print(number) print(args) print(kwargs) f(42, 'a', 'b', 123, z=5, y=7) # # Misc # # * sorted # * any # * all # * sum # * max # * min # ## sorted # In[37]: data = (1, 5, 2, 7, 4) print(sorted(data)) # 排序 # ## all & any # In[38]: data = (True, 1, "asd") print(all(data)) # data 裡的資料是否都為真 print(any(data)) # data 裡的資料是否有一為真 # In[39]: data = (False, 0, "") print(all(data)) # data 裡的資料是否都為真 print(any(data)) # data 裡的資料是否有一為真 # In[40]: data = (True, 0, "") print(all(data)) # data 裡的資料是否都為真 print(any(data)) # data 裡的資料是否有一為真 # ## sum # In[41]: result = sum([1, 2, 3, 4, 5]) print(result) # ## max & min # In[42]: data = [1, 42, 2, 34, 10] print(max(data)) print(min(data)) # # 總複習 # # * List # - List Methods # + list.append # + list.reverse # + list.sort # + list.remove # + list.pop # + list.index # + list.insert # + list.count # * List Comprehension # - 更方便地建立 list # * More String Operations # - A 是否是 B 的子字串 # - 把 B 用空格切割 # - B 是以 "This" 開頭的? # - 找到子字串的位置 # - 字串重複 # - 字串連接 # - 字串用特定分隔符號連接 # * Regular Expressions # * Import # * 自己寫 Module # * Unpack # - 拆解 & 打包 # - `*` : list # - `**` : dictionary # * Misc # - sorted # - any # - all # - sum # - max # - min # # # 其他還有很多還沒包含的議題 (未全部列出) # # ## 更多 Features # # * decorator # * metaclass # * Duck Typing # * Generator # * is v.s. == # * zip # * map # * filter # * reduce # * partial # * closure # * sum # * First-class function # * lambda function # * join # * async, await # * unit testing # # ## pip - Python 套件管理 # # 安裝別人寫的程式 ~ # # ```sh # $ pip search PACKAGE # $ pip install PACKAGE # ``` # # example : # # ```sh # $ pip search requests # $ pip install requests # ``` # # ## Python 記憶體管理方式 (Garbage Collection) # # * CPython : Reference Counting # * PyPy : Incremental Generational Mark-and-Sweep GC # # ## 更多資料結構的資訊 # # * list 適合的操作 (效率) # * collections module # # ## Python 和其他程式語言合作 # # * ctypes (Python & C) # * cffi (Python & C)