???? “Python猫” ,一个值得加星标的公众号
剧照 | 《犬夜叉》
原标题 | Three Ways to Use the Walrus Operator in Python
作 者 | Jonathan Hsu
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")
line = f.readLine()
while line:
print(line)
line = f.readLine()
# 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: ")
if p == "the password":
break
# when converting to walrus operator...
while (p := input("Enter the password: ")) != "the password":
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
优质文章,推荐阅读: