文章目錄
- 簡介
- ??條件判斷優化
- 循環控制簡化?
- 推導式高效計算?
- 正則匹配與數據提取?
- 性能對比
- 參考文獻
簡介
海象運算符 :=
,又稱??賦值表達式??(Assignment Expression),Python 3.8 后可用,PEP 572 引入,其核心設計是在表達式內部完成變量賦值并返回該值,從而簡化代碼邏輯。
正常賦值語句是 a=b
,讀作“a等于b”,而海象賦值語句是 a:=b
,讀作“a walrus /?w??lr?s/ b”,因為 :=
看起來像海象的眼睛和牙齒。
海象運算符優先級低于比較操作,需用括號明確邊界
??條件判斷優化
import datetimeperson = {'name': 'Alice', 'birthyear': 1997}
currentyear = datetime.datetime.now().yearif birthyear := person.get('birthyear'):print(f'{currentyear - birthyear} years old')# 傳統寫法
if person.get('birthyear'):birthyear = person['birthyear'] # 調多一次print(f'{currentyear - birthyear} years old')
避免重復計算,提升可讀性
循環控制簡化?
with open('requirements.txt', encoding='utf-8') as f:while line := f.readline():print(line)# 傳統寫法
with open('requirements.txt', encoding='utf-8') as f:while True:line = f.readline()if not line:breakprint(line)
推導式高效計算?
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]squares = [squared for num in numbers if (squared := num ** 2) > 10] # 計算平方值大于10的結果
print(squares)# 傳統寫法
squares = [num ** 2 for num in numbers if num ** 2 > 10]
print(squares)
正則匹配與數據提取?
import retext = 'Date: 2023-10-05'if (match := re.search(r'(\d{4})-(\d{2})-(\d{2})', text)):year, month, day = match.groups()print(f'{year}-{month}-{day}')# 傳統寫法
match = re.search(r'(\d{4})-(\d{2})-(\d{2})', text)
if match:year, month, day = match.groups()print(f'{year}-{month}-{day}')
性能對比
import timeit
import random# 10萬個隨機整數,計算平方值并篩選大于2500的元素
data = [random.randint(1, 100) for _ in range(100000)]def traditional_method():"""傳統寫法"""return [x ** 2 for x in data if x ** 2 > 2500]def walrus_method():"""海象運算符寫法"""return [sq for x in data if (sq := x ** 2) > 2500]traditional_time = timeit.timeit(traditional_method, number=100)
walrus_time = timeit.timeit(walrus_method, number=100)print(f'傳統寫法耗時: {traditional_time:.4f} 秒')
print(f'海象運算符耗時: {walrus_time:.4f} 秒')
print(f'性能提升: {((traditional_time - walrus_time) / traditional_time) * 100:.2f}%')
# 傳統寫法耗時: 2.0772 秒
# 海象運算符耗時: 1.5260 秒
# 性能提升: 26.53%
參考文獻
- 一文了解 Python 3.8 中的海象運算符
- What’s New In Python 3.8