Python 海象运算符 (:=) 的三种用法

Three Ways to Use the Walrus Operator in Python

| 鸢尾、唐里

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")

While 循环

line = f.readLine()

while line:

print(line)

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

print(line)

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

while True:

p = input("Enter the password: ")

break

# when converting to walrus operator...

continue

列表理解

scores = [22,54,75,89]

valid_scores = [

longFunction(n)

for n in scores

if longFunction(n)

]

scores = [22,54,75,89]

valid_scores = [

result for n in scores

result := longFunction(n)

]

处理返回的数据

# 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)

if records := api.readFailedRecords():

for record in records:

api.assignToTechnician(record)

总结

via https://medium.com/better-programming/three-ways-to-use-the-walrus-operator-in-python-d5550f3a7dd

/ 更多阅读 /

，查看本文更多内容