# Python ###### tags: `python` `lambda` `threading` `@` `random` Outline --- [TOC] CH1 --- ### 函式內函式 **Input:** ```python= def aa(): print("It's begin") def no1(): print("It's no1") return no1 aa()() ``` **Output:** ``` It's begin It's no1 ``` --- ### 字串處理 分割成列表 指定分割符號 txt.split(".") 每行分割 txt.splitlines() 字串反轉 txt[::-1] 字串取代 txt.replace(old, new, max=all) txt[0:3] = "123" 列表集合成字串 "".join(list) --- ### 修飾符 **Input:** ```python= def aa(a): print(a) def cc(f): f() return "finish" return cc @aa("hi") # bb = aa("hi")(bb) def bb(): print("This is b") print(bb) ``` **Output:** ``` hi This is b finish ``` --- ```python= def aa(msg): def a(f): print(f(msg)) def b(f): print("It's b") def c(f): print("It's c") dic = {"hi":a, "jj":b, "uu":c} for i in dic.keys(): if i in msg: return dic[i] text = "hi this a bored guy !" @aa(text) def bb(msg): return msg.split(" ") #print(aa(text)) ``` --- ### 執行緒 **Input:** ```python= import threading import time # 子執行緒的工作函數 def job(): while 1: msg = input("請輸入:\n") print("This is your input : ", msg) # 建立一個子執行緒 t = threading.Thread(target = job) # 執行該子執行緒 t.start() # 主執行緒繼續執行自己的工作 def main(): i = 1 while 1: print(i) i += 1 time.sleep(1) main() # 等待 t 這個子執行緒結束 t.join() ``` **Output:** ``` 1 請輸入: 2 3 4 5 6 hello 7 This is your input : hello 請輸入: 8 9 10 . . . ``` --- ### 字典取值 **Input:** ```python= ''' dict.get(num, default) 從字典取出 num 值,若沒有回傳 default ''' mydict = {1:"itme1", 2:"itme2", 3:"itme3"} print(mydict.get(1, "not item")) # item1 print(mydict.get(4, "not item")) # not item ``` --- ### lambda 匿名函數 **Input:** ```python= lambda x, y: x + y ''' 等同創建一函式 <lambda> 其內容為 def <lambda>(x,y): return x + y ''' #<lambda>不可呼叫 #可用變數呼叫,如下 a = lambda x, y: x + y a(1,2) #3 ``` --- ### 修飾符與 lambda 應用 ```python= def total(number): return { 1 : lambda meal: lambda: meal() + 30, 2 : lambda meal: lambda: meal() + 40, 3 : lambda meal: lambda: meal() + 50, 4 : lambda meal: lambda: meal() + 60 }.get(number, lambda meal: lambda: meal()) @total(2) @total(3) def cola(): return 49.0 print(cola()) # 139.0 ``` --- ### 列表洗牌 ```python= import random # 生成一列表 a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] a = [x for x in range(10)] # 將 a 列表洗牌 b = random.shuffle(a) print(a) ``` --- ### 從網路取得圖片 需事先安裝 wget 套件 --> ```pip install wget``` ```python= import wget url = "https://cf.shopee.tw/file/86a0a0f9b0e557f2f904e45bd4101b9a" status = wget.download(url, out="image.jpg") print('Success' if status == 'image.jpg' else 'error') ``` ※ 若重複執行檔名不會覆蓋,將以 ```image(1).jpg``` 存檔,所以須先刪除舊檔。 --- ### 字串處理 [ascii 表](http://kevin.hwai.edu.tw/~kevin/material/JAVA/Sample2016/ASCII.htm) ``` >>>bytes("python", 'ascii') b'python' >>> ord('a') 97 >>> chr(97) 'a' >>> chr(ord('a') + 3) 'd' >>> unichr(97) u'a' >>> unichr(1234) u'\u04d2' ``` ### 序列埠 ```python= import serial ser = serial.Serial(port='/dev/ttyUSB0', baudrate=9600) while 1: if(ser.in_waiting >0): line = ser.readline() print(line) ``` ### 位元處理 若有一個二進制數值```0b10``` = 2,將之向左移動兩位元```<< 2```,得到之值為```0b1000``` = 8 ```0b10 << 2 | 0b10``` 意思為將```0b10 << 2``` = ```0b1000``` 使用 or 處理```|```,使之成為 ```0b1010``` = 10 ```python= #!/usr/bin/env python # -- coding:UTF-8 #import pyzbar.pyzbar as pyzbar import numpy as np import cv2 cap = cv2.VideoCapture(0) # 選擇攝影機 # Set the video resolution to HD720 (2560*720) resolution = {"2.2k":(4416, 1242), "1080p":(3840, 1080), "720p":(2560, 720), "WVGA":(1344, 376)} resolution = resolution["720p"] cap.set(cv2.CAP_PROP_FRAME_WIDTH, resolution[0]) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, resolution[1]) #cap.set(cv2.CAP_PROP_FPS, 15) # Main if __name__ == '__main__': i = 15 while 1: _, frame = cap.read() left_right_frame = np.split(frame, 2, axis=1) #lframe = np.hstack((left_right_frame[1],left_right_frame[2])) #rframe = np.hstack((left_right_frame[3],left_right_frame[4])) lframe = left_right_frame[0] rframe = left_right_frame[1] #j += 1 #cv2.putText(rframe, str(j), (100,100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,155,255), 2, cv2.LINE_AA) #cv2.imshow('frame', frame) # 顯示圖片 cv2.imshow('Lframe', lframe) # 顯示圖片 cv2.imshow('Rframe', rframe) # 顯示圖片 # 若按下 q 鍵則離開迴圈 k = cv2.waitKey(1) if k == ord('c'): i += 1 cv2.imwrite(f'''img/Left/{i}.png''', lframe) # 顯示圖片 cv2.imwrite(f'''img/Right/{i}.png''', rframe) # 顯示圖片 print("I read !") elif k == ord('q'): break cap.release() # 釋放攝影機 cv2.destroyAllWindows() # 關閉所有 OpenCV 視窗 ``` [深度圖](https://gist.github.com/aarmea/629e59ac7b640a60340145809b1c9013)