Python walrus operator in detail

Walrus operator definition:
a variable name followed by an expression or a value, this is a new assignment operator.
Here are three ways to use it:

1. For if else conditional expression

Basic writing:

x=5
if x<10:
    print("hello fancy!")

Walrus operator writing:

if (x:=5) < 10:
    print("hello fancy!")

operation result:
insert image description here

Two, for while loop

Basic writing:

num=3
while num:
    print(f"{
      
      num}")
    num-=1

operation result:
insert image description here

Walrus operator writing:

num=3
while (num:=num-1)+1:
	print(f"{
      
      num}")

operation result:
insert image description here

Three, for derivation

Basic writing:

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)

Running result:
insert image description here
Written by walrus operator:

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)

operation result:
insert image description here

It can be seen that using the walrus operator can save function calls and improve performance.

Here f "f(x) function has been run {count} times" is a format conversion, if f is not added, this will happen:
insert image description here

Guess you like

Origin blog.csdn.net/fancynthia/article/details/126394452