简介
海象运算符 :=,又称赋值表达式(assignment expression),python 3.8 后可用,pep 572 引入,其核心设计是在表达式内部完成变量赋值并返回该值,从而简化代码逻辑。
正常赋值语句是 a=b,读作“a等于b”,而海象赋值语句是 a:=b,读作“a walrus /ˈwɔːlrəs/ b”,因为 := 看起来像海象的眼睛和牙齿。
海象运算符优先级低于比较操作,需用括号明确边界
条件判断优化
import datetime
person = {'name': 'alice', 'birthyear': 1997}
currentyear = datetime.datetime.now().year
if 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:
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) # 传统写法 squares = [num ** 2 for num in numbers if num ** 2 > 10] print(squares)
正则匹配与数据提取
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}')
# 传统写法
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海象运算符:=的具体实现的文章就介绍到这了,更多相关python海象运算符内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论