海象运算符定义:
一个变量名跟一个表达式或者一个值,这个是一种新的 赋值运算符。
下面看看它的三种用法:
一、用于if else 条件表达式
基础写法:
x=5
if x<10:
print("hello fancy!")
海象运算符写法:
if (x:=5) < 10:
print("hello fancy!")
运行结果:
二、用于while循环
基础写法:
num=3
while num:
print(f"{
num}")
num-=1
运行结果:
海象运算符写法:
num=3
while (num:=num-1)+1:
print(f"{
num}")
运行结果:
三、用于推导式
基础写法:
num1=[1,2,3,4,5]
count=1
def f(x):
global count
print(f"f(x)函数运行了{
count}次")
count+=1
return x**2
num2 = [f(x) for x in num1 if f(x) > 10 ]
print(num2)
运行结果:
海象运算符写法:
num1=[1,2,3,4,5]
count=1
def f(x):
global count
print(f"f(x)函数运行了{
count}次")
count+=1
return x**2
num2 = [n for x in num1 if ( n:= f(x) ) > 10 ]
print(num2)
运行结果:
可以看到,使用海象运算符可以节省函数调用,起到提升性能的作用。
这里 f"f(x)函数运行了{count}次" 是格式转换,如果不加 f 就会出现这样的情况: