Python海象運算符:=的具體實現(xiàn)
簡介
海象運算符 :=,又稱??賦值表達式??(Assignment Expression),Python 3.8 后可用,PEP 572 引入,其核心設計是在表達式內部完成變量賦值并返回該值,從而簡化代碼邏輯。
正常賦值語句是 a=b,讀作“a等于b”,而海象賦值語句是 a:=b,讀作“a walrus /?w??lr?s/ b”,因為 := 看起來像海象的眼睛和牙齒。
海象運算符優(yōu)先級低于比較操作,需用括號明確邊界
??條件判斷優(yōu)化
import datetime
person = {'name': 'Alice', 'birthyear': 1997}
currentyear = datetime.datetime.now().year
if birthyear := person.get('birthyear'):
print(f'{currentyear - birthyear} years old')
# 傳統(tǒng)寫法
if person.get('birthyear'):
birthyear = person['birthyear'] # 調多一次
print(f'{currentyear - birthyear} years old')
避免重復計算,提升可讀性
循環(huán)控制簡化?
with open('requirements.txt', encoding='utf-8') as f:
while line := f.readline():
print(line)
# 傳統(tǒng)寫法
with open('requirements.txt', encoding='utf-8') as f:
while True:
line = f.readline()
if not line:
break
print(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) # 傳統(tǒng)寫法 squares = [num ** 2 for num in numbers if num ** 2 > 10] print(squares)
正則匹配與數(shù)據(jù)提取?
import re
text = '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}')
# 傳統(tǒng)寫法
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萬個隨機整數(shù),計算平方值并篩選大于2500的元素
data = [random.randint(1, 100) for _ in range(100000)]
def traditional_method():
"""傳統(tǒng)寫法"""
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'傳統(tǒng)寫法耗時: {traditional_time:.4f} 秒')
print(f'海象運算符耗時: {walrus_time:.4f} 秒')
print(f'性能提升: {((traditional_time - walrus_time) / traditional_time) * 100:.2f}%')
# 傳統(tǒng)寫法耗時: 2.0772 秒
# 海象運算符耗時: 1.5260 秒
# 性能提升: 26.53%
到此這篇關于Python海象運算符:=的具體實現(xiàn)的文章就介紹到這了,更多相關Python海象運算符內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python Miniforge3 環(huán)境配置的實現(xiàn)
這篇文章主要介紹了Python Miniforge3 環(huán)境配置的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考,一起跟隨小編過來看看吧2017-11-11
Python cookbook(數(shù)據(jù)結構與算法)從序列中移除重復項且保持元素間順序不變的方法
這篇文章主要介紹了Python cookbook(數(shù)據(jù)結構與算法)從序列中移除重復項且保持元素間順序不變的方法,涉及Python針對列表與字典的元素遍歷、判斷、去重、排序等相關操作技巧,需要的朋友可以參考下2018-03-03
Python 中獲取數(shù)組的子數(shù)組示例詳解
在 Python 中獲取一個數(shù)組的子數(shù)組時,可以使用切片操作,使用切片操作來獲取一個數(shù)組的一段連續(xù)的子數(shù)組,并且還可以使用一些方便的語法來簡化代碼,這篇文章主要介紹了如何在 Python 中獲取數(shù)組的子數(shù)組,需要的朋友可以參考下2023-05-05

