程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Three uses of Python walrus operator (: =)

編輯:Python

With Python 3.8 Release , Assignment expression operator ( Also known as walrus operator ) Also released .
Operator allows the assignment of a value to be passed into an expression . This usually reduces the number of statements by one . for example :

my_list = [1,2,3]
count = len(my_list)
if count > 3:
print(f"Error, {count} is too many items")
# when converting to walrus operator...
if (count := len(my_list)) > 3:
print(f"Error, {count} is too many items")

If you take a quick look , You will understand the concern about this new operation . Seems to confuse two simple statements , To minimize benefits .
Suppose you have a reasonable answer to why this operator was introduced ? It makes people naturally think of , How it works in the real world ?
I found three aspects of walrus operators that I will continue to use , And each aspect can bring other benefits besides saving a line of code .

While loop
Although loops seem to be the most common use of walrus operators . The advantage of using walrus operators here is that they can be used in while Combine expressions and modifiers in statements . I've written countless infinite cycles , Because I always forget to write modification statements at the end of the loop .

line = f.readLine()
while line:
print(line)
line = f.readLine()
# when converting to walrus operator...while line := f.readLine():
print(line)

But be careful , Walrus operators are more suitable for traditional do/while loop , Because the assignment is before the loop expression . See differences below :

n = 0
while n < 3:
print(n) # 0,1,2
n += 1
# when converting to walrus operator...
w = 0
while (w := w + 1) < 3:
print(w) # 1,2

Based on my limited experience , I find it replacing infinity while Most useful in the loop :

while True:
p = input("Enter the password: ")
if p == "the password":
break
# when converting to walrus operator...
while (p := input("Enter the password: ")) != "the password":
continue

To be able to while It's great to turn a loop into a statement .

List understanding
I find walrus operators helpful in optimizing some list comprehension statements . There are two criteria 1) Need to filter data ,2) Storage taxing function Result . Let's look at the traditional list understanding statement :

scores = [22,54,75,89]
valid_scores = [
longFunction(n)
for n in scores
if longFunction(n)
]

Pay attention to conditional statements longFunction(n) Did you? ? Be careful longFunction() Has it been called twice ? This is a candidate for walrus operators .

scores = [22,54,75,89]
valid_scores = [
result for n in scores
result := longFunction(n)
]

In optimized code ,longFunction() Only called once , Implicitly reduces the number of calls .

Process the returned data
Next is what I think is the most useful implementation of the walrus operator . I often use the term iFormBuilder Mobile data collection software . say concretely , Request record ( data row ) after , When querying the returned data , It needs to be dealt with . This is the code block I write every day :

# look for failed inspections
# if there are failed inspections, assign to technicianrecords = api.readFailedRecords()
if len(records) > 0:
for record in records:
api.assignToTechnician(record)

I read the records carefully , Carefully type the code , To ensure that the code block executes only when the returned list has data :

if records := api.readFailedRecords():
for record in records:
api.assignToTechnician(record)

In terms of readability , This refactoring is least disruptive , actually , I find that in this case , Walrus operators are easier to read . In sharp contrast to the previous two examples , The first two examples have less impact on readability , It helps to save worry and improve performance .

summary
Walrus operators are novel and controversial , But only time will tell that it is gradually accepted by everyone . Have you started using it in your code ?

The above is all the content shared this time , Want to know more python Welcome to official account :Python Programming learning circle , send out “J” Free access to , Daily dry goods sharing


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved