其他
Python 海象运算符 := 的三种用法
(给Python开发者加星标,提升Python技能)
编译:AI开发者(okweiwu)-人气呆毛选手,作 者 : 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)
总结
推荐阅读
(点击标题可跳转阅读)
觉得本文对你有帮助?请分享给更多人
关注「Python开发者」加星标,提升Python技能
好文章,我在看❤️