python3.8中的新特性,":="符号assignment Expressions,翻译过来也就是赋值表达式,大家更普遍地称之为海象运算符。
1. 第一个用法:if/else #
if (age:= 20) > 18: print("已经成年了")
2. 第二个用法:while #
file = open("demo.txt", "r") while (line := file.readline()): print(line.strip())
比如,实现一个需要命令行交互输入密码并检验的代码,你也许会这样子写
while True: p = input("Enter the password: ") if p == "youpassword": break
有了海象运算符之后,这样子写更为舒服
(p := input("Enter the password: ")) != "youpassword": continue
3. 第三个用法:推导式 #
members = [ {"name": "小五", "age": 23, "height": 1.75, "weight": 72}, {"name": "小李", "age": 17, "height": 1.72, "weight": 63}, {"name": "小陈", "age": 20, "height": 1.78, "weight": 82},] # 查出所有会员中过于肥胖的人的 bmi 指数 fat_bmis = [bmi for m in members if (bmi := get_bmi(m)) > 24]
最终从输出结果可以看出,只执行了 3 次
执行了 1 次执行了 2 次执行了 3 次[25.88057063502083]
不仅在列表推导式,在字典推导式和集合推导式中同样适用。