# 前言

這篇筆記僅會記錄一些我覺得比較特別的語法跟我熟悉的 C++ 差異比較大的部分,並不會系統性的介紹所有語法。
還有一些 python 常用套件的語法。

# 語法介紹

# 單行 if(三元運算子)

Python 沒有 ? : 運算子,而是用以下語法表達:

值A if 條件 else 值B
x = 10
result = "big" if x > 5 else "small"
# result = "big"
# 可直接用在運算式或函式參數中
print("even" if x % 2 == 0 else "odd")
# 可巢狀(不建議超過兩層,可讀性差)
label = "high" if x > 8 else "mid" if x > 4 else "low"

單行 if 沒有 else 的版本只能用在 Comprehension 的篩選條件,不能單獨用在賦值:

# 合法:用在 Comprehension 篩選(沒有 else)
[x for x in range(10) if x % 2 == 0]
# 不合法:單獨賦值時沒有 else 會報錯
result = x if x > 5  # SyntaxError

# Comprehension(推導式)

將 for 迴圈濃縮成一行的語法,根據包裝的括號不同,產生不同的資料結構。

# List Comprehension(列表推導式)

# 基本
[x * 2 for x in range(5)]
# [0, 2, 4, 6, 8]
# 搭配 if 篩選
[x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]
# 搭配三元 if/else
[f"small-{x}" if x <= 3 else str(x) for x in range(1, 6)]
# ['small-1', 'small-2', 'small-3', '4', '5']

# Set Comprehension(集合推導式)

# 基本
{x * 2 for x in range(5)}
# {0, 2, 4, 6, 8}
# 搭配 if 篩選
{x for x in range(10) if x % 2 == 0}
# {0, 2, 4, 6, 8}
# 搭配三元 if/else
{"small" if x <= 3 else "big" for x in range(1, 6)}
# {'small', 'big'}

# Dict Comprehension(字典推導式)

# 基本
{x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 搭配 if 篩選
{x: x**2 for x in range(10) if x % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# 搭配三元 if/else
{x: ("small" if x <= 3 else "big") for x in range(1, 6)}
# {1: 'small', 2: 'small', 3: 'small', 4: 'big', 5: 'big'}

# Generator Expression(生成器表達式)

不會一次產生整個資料結構,而是逐個產生值,適合大量資料時節省記憶體。

# 基本
(x * 2 for x in range(5))
# 搭配 if 篩選
(x for x in range(10) if x % 2 == 0)
# 搭配三元 if/else
(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)  # 5
# 搭配 sorted
words = ["banana", "apple", "cherry"]
sorted(words, key=lambda w: len(w))
# ['apple', 'banana', 'cherry']

# map

對可迭代物件的每個元素套用函式,回傳一個 map 物件(惰性求值)。

# 基本語法
map(函式, 可迭代物件)
# 範例
list(map(lambda x: x**2, [1, 2, 3, 4]))
# [1, 4, 9, 16]
# 搭配內建函式
list(map(str, [1, 2, 3]))
# ['1', '2', '3']
# 多個可迭代物件
list(map(lambda x, y: x + y, [1, 2, 3], [10, 20, 30]))
# [11, 22, 33]

# zip

將多個可迭代物件「拉鍊」合併,逐一配對成 tuple。

# 基本語法
zip(可迭代物件1, 可迭代物件2, ...)
# 範例
names = ["Alice", "Bob", "Carol"]
scores = [90, 85, 92]
list(zip(names, scores))
# [('Alice', 90), ('Bob', 85), ('Carol', 92)]
# 常見用法:同時迭代兩個列表
for name, score in zip(names, scores):
    print(name, score)
# 長度不同時,以最短的為準
list(zip([1, 2, 3], ["a", "b"]))
# [(1, 'a'), (2, 'b')]

# reduce

對可迭代物件進行累積運算,需從 functools 匯入。

from functools import reduce
# 基本語法
reduce(函式, 可迭代物件, 初始值)
# 範例:累加
reduce(lambda acc, x: acc + x, [1, 2, 3, 4, 5])
# 15
# 有初始值
reduce(lambda acc, x: acc + x, [1, 2, 3], 100)
# 106
# 找最大值
reduce(lambda a, b: a if a > b else b, [3, 1, 4, 1, 5, 9])
# 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
)
# 省略 x(自動以 0,1,2... 為索引)
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()                    # 顯示圖例(需各繪圖函式有設 label)
plt.xlim(0, 10)                 # 設定 X 軸範圍
plt.ylim(-1, 15)                # 設定 Y 軸範圍
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()
# 2x2 格線
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))             # 全 0
np.ones((2, 4))              # 全 1
np.arange(0, 10, 2)         # [0, 2, 4, 6, 8]
np.linspace(0, 1, 5)        # [0, 0.25, 0.5, 0.75, 1.0]
# 向量化運算(不需要 for 迴圈)
a = np.array([1, 2, 3])
a * 2       # [2, 4, 6]
a ** 2      # [1, 4, 9]
a + a       # [2, 4, 6]
# 常用屬性
a.shape     # (3,)
a.dtype     # int64
a.ndim      # 1
# 常用函式
np.sum(a)       # 6
np.mean(a)      # 2.0
np.max(a)       # 3
np.min(a)       # 1
np.sort(a)      # 排序

# shape

shape 是陣列的屬性(不是函式),回傳一個 tuple,代表陣列每個維度的大小。

a = np.array([1, 2, 3])
a.shape         # (3,)        一維,3 個元素
b = np.array([[1, 2, 3], [4, 5, 6]])
b.shape         # (2, 3)      二維,2 列 3 欄
c = np.zeros((2, 3, 4))
c.shape         # (2, 3, 4)   三維
# 常見用法:取出資料維度
X_train = np.array([[1, 2], [3, 4], [5, 6]])
X_train.shape[0]    # 3,樣本數(列數)
X_train.shape[1]    # 2,特徵數(欄數)

# np.zeros

np.zeros(shape, dtype=float) :建立指定形狀、內容全為 0 的陣列。

  • shape :可以是整數(一維)或 tuple(多維)
  • dtype :預設為 float64 ,可省略
np.zeros(3)          # array ([0., 0., 0.])          shape 傳整數 -> 一維陣列
np.zeros((3,))       # array ([0., 0., 0.])          等同上面,用 tuple 表示一維
np.zeros((2, 3))     # 2x3 全 0 陣列
np.zeros((2, 3), dtype=int)  # 指定型別為整數
# 實際範例:初始化線性模型參數
data_dim = 4                    # 特徵數量
w = np.zeros(data_dim)          # shape=(4,),每個特徵一個權重
b = np.zeros(1)                 # shape=(1,),一個偏差值
print(w)    # [0. 0. 0. 0.]
print(b)    # [0.]
更新於 閱讀次數 次