Python 3.8 引入了一個外型奇特、但非常實用的新語法:
**海象運算子(Walrus Operator,`:=`)**。
很多介紹都停留在 `if` 或 `while` 的簡單例子,
但在實務中,
**它真正發揮價值的地方,其實是在資料清洗與文字處理**。
本文就用一個「實際可上線的斷詞場景」,來說明:
**什麼時候該用海象運算子,以及為什麼這樣用是對的。**
— ## 什麼是海象運算子?
海象運算子是 Python 的「**表達式內賦值運算子**」:
:=一句話定義:
在「需要一個值的地方」,同時完成「賦值」與「使用」。
它不是用來取代一般的 =,
而是用在 expression(表達式) 裡。
真實使用場景:斷詞+清洗+過濾
假設我們在做文字斷詞,需要:
- Jieba 斷詞
- 去空白
- 轉小寫
- 移除 Stopwords
- 收集乾淨的 tokens
傳統寫法(for-loop)
tokens = []
for w in words:
w_clean = w.strip().lower()
if w_clean and w_clean not in STOPWORDS:
tokens.append(w_clean)這段程式碼 完全沒錯,也很清楚。
但可以觀察到兩件事:
w_clean只是「中間結果」- 它的生命週期只用在這個判斷裡
用海象運算子重寫
tokens = [
w_clean for w in words
if (w_clean := w.strip().lower()) and w_clean not in STOPWORDS
]![Python 表達式中的魔法:用海象運算子讓斷詞程式碼更乾淨 [w_clean for w in words if (w_clean:=w.lower().strip()) and w_clean not in STOPWORDS] - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2026/02/20260210083748_0_a7d9bf.png)
我們來逐步理解這一行在做什麼。
逐步拆解這個表達式
1️⃣ 表達式內賦值
(w_clean := w.strip().lower())這一行同時完成兩件事:
- 計算
w.strip().lower() - 把結果存進
w_clean
而且,整個表達式的值就是 w_clean 本身。
2️⃣ 利用短路邏輯做過濾
(w_clean := ...) and w_clean not in STOPWORDS- 如果
w_clean是空字串 → 直接丟掉 - 如果在
STOPWORDS→ 丟掉 - 否則 → 通過
✅ 沒有重複計算
✅ 沒有額外變數
✅ 邏輯集中在同一個地方
3️⃣ 收集結果
w_clean for w in words if ...通過條件的時候,
使用的正是 剛剛算好的 w_clean。
為什麼這裡「非常適合」用海象運算子?
這個場景同時滿足了三個條件:
- ✅ 中間結果只用一次
- ✅ 避免重複計算
- ✅ 變數生命週期應該很短
這正是 PEP 572 官方推薦的使用方式。
常見誤解:一定要搭配 if / while?
❌ 錯誤理解:
海象運算子只能用在
if或while
✅ 正確理解:
海象運算子可以用在任何「表達式」裡
而 list comprehension 的 if 條件,
本身就是一個表達式。
什麼時候「不該」用海象運算子?
以下情況請避免:
- 表達式太長,影響可讀性
- 為了炫技而用
- 讓變數的作用範圍變得不清楚
例如:
if (a := f(x)) and (b := g(a)) and h(b):
...一句話總結
海象運算子不是為了少寫一行,
而是為了讓「計算、判斷、使用」待在同一個語意單位裡。
在資料清洗、斷詞、過濾這類 pipeline 中,
它能讓程式碼 更緊湊、也更聚焦意圖。
如果你寫的是偏工程、偏 IR、偏 NLP 的 Python 程式,
這會是你最常「正確用到」海象運算子的地方。
推薦hahow線上學習python: https://igrape.net/30afN
定義:什麼是「表達式(Expression)」
在 Python 中,**表達式(expression)**指的是:
「會被求值(evaluate),並且產生一個結果值的語法結構。」
只要一段程式碼 能被計算出一個值,它就是表達式。
✅ 表達式的三個關鍵特徵
- 會被計算(evaluate)
- 計算後有「值」
- 可以出現在「需要一個值的地方」
✅ 常見的表達式範例
1 + 2 # 3
len(data) # 一個整數
w.strip().lower() # 一個字串
x > 0 # True / False這些都會產生「值」,因此都是表達式。
❌ 不是表達式的例子(Statement)
x = 10
def foo(): ...
for i in range(5): ...這些是 敘述(statement):
- 用來「做事」
- 本身 不產生值
- 不能被拿去當成條件或傳給函式
🧠 為什麼這個定義對海象運算子很重要?
海象運算子 := 的設計核心就是:
只能出現在「表達式」中,而不能當成獨立的敘述使用。
✅ 合法(在表達式中)
if (n := len(data)) > 10:
print(n)❌ 不合法(單獨敘述)
n := len(data) # SyntaxError因為這一行 不是表達式環境。
✅ 常見的「表達式容器」
以下結構「裡面放的東西」都是表達式:
if/while條件- list / dict / set comprehension
- generator expression
assertreturn- 函式呼叫的參數
這也是為什麼海象運算子常見於這些地方。
🧠 一句話版定義(教學用金句)
表達式 = 會被算出一個值的東西。
海象運算子 = 在表達式裡,一邊賦值、一邊使用這個值。
推薦hahow線上學習python: https://igrape.net/30afN


![Python list[] dictionary{key: value},如何從兩個list,建立一個dictionary? Python list[] dictionary{key: value},如何從兩個list,建立一個dictionary?](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2022/09/20220904074100_2.png?quality=90&zoom=2&ssl=1&resize=350%2C233)


![Python: list.index() 只能找到第一個元素的index,若元素有重複,如何找出所有index? indexes = [index for index, value in enumerate(my_list) if value == target] Python: list.index() 只能找到第一個元素的index,若元素有重複,如何找出所有index? indexes = [index for index, value in enumerate(my_list) if value == target]](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2024/10/20241010101216_0_12b6c0.png?quality=90&zoom=2&ssl=1&resize=350%2C233)


![Python: 如何求整個 pandas.DataFrame 中的最大值? pandas.DataFrame .max().max() ; 如何求最大值的index, columns? numpy.where(condition, [x, y, ]/) ; condition為一 bool_mask Python: 如何求整個 pandas.DataFrame 中的最大值? pandas.DataFrame .max().max() ; 如何求最大值的index, columns? numpy.where(condition, [x, y, ]/) ; condition為一 bool_mask](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2023/04/20230418154049_50.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

近期留言