# 前言
這篇筆記僅會記錄一些我覺得比較特別的語法跟我熟悉的 C++ 差異比較大的部分,並不會系統性的介紹所有語法。
還有一些 python 常用套件的語法。
# 語法介紹
# 單行 if(三元運算子)
Python 沒有 ? : 運算子,而是用以下語法表達:
| x = 10 |
| result = "big" if x > 5 else "small" |
| |
| |
| |
| print("even" if x % 2 == 0 else "odd") |
| |
| |
| label = "high" if x > 8 else "mid" if x > 4 else "low" |
單行 if 沒有 else 的版本只能用在 Comprehension 的篩選條件,不能單獨用在賦值:
| |
| [x for x in range(10) if x % 2 == 0] |
| |
| |
| result = x if x > 5 |
# Comprehension(推導式)
將 for 迴圈濃縮成一行的語法,根據包裝的括號不同,產生不同的資料結構。
# List Comprehension(列表推導式)
| |
| [x * 2 for x in range(5)] |
| |
| |
| |
| [x for x in range(10) if x % 2 == 0] |
| |
| |
| |
| [f"small-{x}" if x <= 3 else str(x) for x in range(1, 6)] |
| |
# Set Comprehension(集合推導式)
| |
| {x * 2 for x in range(5)} |
| |
| |
| |
| {x for x in range(10) if x % 2 == 0} |
| |
| |
| |
| {"small" if x <= 3 else "big" for x in range(1, 6)} |
| |
# Dict Comprehension(字典推導式)
| |
| {x: x**2 for x in range(5)} |
| |
| |
| |
| {x: x**2 for x in range(10) if x % 2 == 0} |
| |
| |
| |
| {x: ("small" if x <= 3 else "big") for x in range(1, 6)} |
| |
# Generator Expression(生成器表達式)
不會一次產生整個資料結構,而是逐個產生值,適合大量資料時節省記憶體。
| |
| (x * 2 for x in range(5)) |
| |
| |
| (x for x in range(10) if x % 2 == 0) |
| |
| |
| (f"small-{x}" if x <= 3 else str(x) for x in range(1, 6)) |
| |
| |
| sum(x**2 for x in range(10)) |
| print(x for x in range(5)) |
# lambda
匿名函式,適合用在需要傳入函式的場合(如 map 、 sorted )。
| |
| lambda 參數: 運算式 |
| |
| |
| add = lambda x, y: x + y |
| add(2, 3) |
| |
| |
| words = ["banana", "apple", "cherry"] |
| sorted(words, key=lambda w: len(w)) |
| |
# map
對可迭代物件的每個元素套用函式,回傳一個 map 物件(惰性求值)。
| |
| map(函式, 可迭代物件) |
| |
| |
| list(map(lambda x: x**2, [1, 2, 3, 4])) |
| |
| |
| |
| list(map(str, [1, 2, 3])) |
| |
| |
| |
| list(map(lambda x, y: x + y, [1, 2, 3], [10, 20, 30])) |
| |
# zip
將多個可迭代物件「拉鍊」合併,逐一配對成 tuple。
| |
| zip(可迭代物件1, 可迭代物件2, ...) |
| |
| |
| names = ["Alice", "Bob", "Carol"] |
| scores = [90, 85, 92] |
| list(zip(names, scores)) |
| |
| |
| |
| for name, score in zip(names, scores): |
| print(name, score) |
| |
| |
| list(zip([1, 2, 3], ["a", "b"])) |
| |
# reduce
對可迭代物件進行累積運算,需從 functools 匯入。
| from functools import reduce |
| |
| |
| reduce(函式, 可迭代物件, 初始值) |
| |
| |
| reduce(lambda acc, x: acc + x, [1, 2, 3, 4, 5]) |
| |
| |
| |
| reduce(lambda acc, x: acc + x, [1, 2, 3], 100) |
| |
| |
| |
| reduce(lambda a, b: a if a > b else b, [3, 1, 4, 1, 5, 9]) |
| |
# matplotlib.pyplot
Python 最常用的繪圖套件。
| import matplotlib.pyplot as plt |
# plt.plot () — 折線圖
| plt.plot(x, y, fmt, **kwargs) |
| 參數 |
型態 |
說明 |
x |
list /ndarray/ 可迭代 |
X 軸資料,可省略(省略時以索引為 x) |
y |
list /ndarray/ 可迭代 |
Y 軸資料(必填) |
fmt |
str |
格式字串,組合顏色 + 標記 + 線型,如 'r--o' |
color |
str |
線條顏色,如 'red' 、 '#FF0000' 、 (1,0,0) |
linewidth / lw |
float |
線條寬度,預設 1.5 |
linestyle / ls |
str |
線型: '-' 、 '--' 、 '-.' 、 ':' 、 'None' |
marker |
str |
資料點標記: 'o' 、 's' 、 '^' 、 'x' 、 '.' 等 |
markersize / ms |
float |
標記大小 |
label |
str |
圖例文字,搭配 plt.legend() 使用 |
alpha |
float (0~1) |
透明度,0 全透明,1 不透明 |
zorder |
int |
繪圖層序,數值越大越在上層 |
fmt 格式字串語法: '[顏色][標記][線型]'
| 類別 |
常用值 |
| 顏色 |
b 藍、 g 綠、 r 紅、 c 青、 m 洋紅、 y 黃、 k 黑、 w 白 |
| 標記 |
o 圓、 s 方、 ^ 三角、 x X、 + 加、 * 星、 . 點 |
| 線型 |
- 實線、 -- 虛線、 -. 點虛線、 : 點線 |
| x = [1, 2, 3, 4, 5] |
| y = [2, 4, 1, 8, 3] |
| |
| |
| plt.plot(x, y) |
| |
| |
| plt.plot(x, y, 'r--o') |
| |
| |
| plt.plot(x, y, |
| color='steelblue', |
| linewidth=2, |
| linestyle='--', |
| marker='o', |
| markersize=8, |
| label='series A', |
| alpha=0.8 |
| ) |
| |
| |
| plt.plot(y) |
# plt.bar () — 長條圖
| plt.bar(x, height, width=0.8, bottom=0, align='center', **kwargs) |
| 參數 |
型態 |
說明 |
x |
list / ndarray |
每根長條的 X 位置 |
height |
list / ndarray |
每根長條的高度 |
width |
float / list |
長條寬度,預設 0.8 |
bottom |
float / list |
長條底部起點,堆疊圖時使用 |
align |
str |
'center' (預設)或 'edge' |
color |
str / list |
填充顏色 |
edgecolor |
str |
邊框顏色 |
label |
str |
圖例文字 |
| categories = ['A', 'B', 'C', 'D'] |
| values = [3, 7, 2, 9] |
| |
| plt.bar(categories, values, color='steelblue', edgecolor='black', width=0.6) |
# plt.scatter () — 散佈圖
| plt.scatter(x, y, s=None, c=None, marker='o', cmap=None, alpha=None, **kwargs) |
| 參數 |
型態 |
說明 |
x |
list / ndarray |
X 軸資料 |
y |
list / ndarray |
Y 軸資料 |
s |
float / list |
每個點的大小(面積),預設約 36 |
c |
str / list / ndarray |
每個點的顏色,可傳入數值陣列搭配 cmap |
marker |
str |
標記形狀,同 plot() |
cmap |
str |
colormap 名稱,如 'viridis' 、 'plasma' 、 'coolwarm' |
alpha |
float |
透明度 |
edgecolors |
str |
點的邊框顏色 |
| import numpy as np |
| x = np.random.randn(100) |
| y = np.random.randn(100) |
| sizes = np.random.randint(20, 200, 100) |
| colors = np.random.rand(100) |
| |
| plt.scatter(x, y, s=sizes, c=colors, cmap='viridis', alpha=0.7, edgecolors='k') |
| plt.colorbar() |
# 常用標籤與版面設定
| plt.title("標題", fontsize=14, fontweight='bold') |
| plt.xlabel("X 軸標籤", fontsize=12) |
| plt.ylabel("Y 軸標籤", fontsize=12) |
| plt.legend() |
| plt.xlim(0, 10) |
| plt.ylim(-1, 15) |
| plt.xticks([1,2,3], ['A','B','C']) |
| plt.grid(True, linestyle='--', alpha=0.5) |
| plt.tight_layout() |
| plt.savefig('output.png', dpi=150, bbox_inches='tight') |
| plt.show() |
# plt.subplots () — 多圖並排
| fig, axes = plt.subplots(nrows, ncols, figsize=(寬, 高), **kwargs) |
| 參數 |
型態 |
說明 |
nrows |
int |
列數,預設 1 |
ncols |
int |
欄數,預設 1 |
figsize |
tuple (w, h) |
整張圖的尺寸,單位為英吋 |
sharex |
bool / str |
是否共用 X 軸 |
sharey |
bool / str |
是否共用 Y 軸 |
| x = [1, 2, 3, 4, 5] |
| y = [2, 4, 1, 8, 3] |
| |
| |
| fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4)) |
| ax1.plot(x, y, 'b-o') |
| ax1.set_title("折線圖") |
| ax2.bar(x, y, color='orange') |
| ax2.set_title("長條圖") |
| plt.tight_layout() |
| plt.show() |
| |
| |
| fig, axes = plt.subplots(2, 2, figsize=(10, 8)) |
| axes[0, 0].plot(x, y) |
| axes[0, 1].bar(x, y) |
| axes[1, 0].scatter(x, y) |
| axes[1, 1].hist(y, bins=5) |
| plt.tight_layout() |
| plt.show() |
# numpy
科學計算套件,核心是 ndarray(N 維陣列),支援向量化運算。
| import numpy as np |
| |
| |
| np.array([1, 2, 3]) |
| np.array([[1, 2], [3, 4]]) |
| np.zeros((3, 3)) |
| np.ones((2, 4)) |
| np.arange(0, 10, 2) |
| np.linspace(0, 1, 5) |
| |
| |
| a = np.array([1, 2, 3]) |
| a * 2 |
| a ** 2 |
| a + a |
| |
| |
| a.shape |
| a.dtype |
| a.ndim |
| |
| |
| np.sum(a) |
| np.mean(a) |
| np.max(a) |
| np.min(a) |
| np.sort(a) |
# shape
shape 是陣列的屬性(不是函式),回傳一個 tuple,代表陣列每個維度的大小。
| a = np.array([1, 2, 3]) |
| a.shape |
| |
| b = np.array([[1, 2, 3], [4, 5, 6]]) |
| b.shape |
| |
| c = np.zeros((2, 3, 4)) |
| c.shape |
| |
| |
| X_train = np.array([[1, 2], [3, 4], [5, 6]]) |
| X_train.shape[0] |
| X_train.shape[1] |
# np.zeros
np.zeros(shape, dtype=float) :建立指定形狀、內容全為 0 的陣列。
shape :可以是整數(一維)或 tuple(多維)
dtype :預設為 float64 ,可省略
| np.zeros(3) |
| np.zeros((3,)) |
| np.zeros((2, 3)) |
| np.zeros((2, 3), dtype=int) |
| |
| |
| data_dim = 4 |
| w = np.zeros(data_dim) |
| b = np.zeros(1) |
| print(w) |
| print(b) |