Python高階應用
1、條件表示式
# -*- coding:utf-8 -*-
import math # 定義一個函式輸入大於零取log,否則返回nan def get_log(x): if x > 0: #技巧在jupyter中檢視python內建函式方法:shift + tab y = math.log(x,10) #Docstring: #log(x[, base]) #Return the logarithm of x to the given base
else: y = float("nan") return y
x = 10 log_val1 = get_log(x) print(log_val1) 1.0
# -*- coding:utf-8 -*-
import math x = 10 log_val2 = math.log(x,10) if x > 0 else float('nan') print(log_val2) 1.0
兩種情況的結果是一樣的,但程式碼的書寫量卻相差很大。
2. 列表推導式
下面程式碼在jupyter中執行:
# -*- coding:utf-8 -*-
%%timeit # 找出100000內的偶數(for迴圈) l1 = [] for i in range(100000): if i % 2 == 0: l1.append(i) 輸出:11.1 ms ± 462 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit # 找出10000內的偶數(列表推導式) l2 = [i for i in range(100000) if i % 2 == 0] 輸出:7.25 ms ± 105 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)