它的英文原名叫Assignment Expressions,翻译过来也就是赋值表达式,不过现在大家更普遍地称之为海象运算符,就是因为它长得真的太像海象了。
海象运算符使值的赋值可以传递到表达式中。 这通常会使语句数减少一个
在 Golang 中的条件语句可以直接在 if 中运算变量的获取后直接对这个变量进行判断
import "fmt"
func main() {
if age := 20;age > 18 {
fmt.Println("已经成年了")
}
}
在 Python 3.8 之前,Python 必须得这样子写
age = 20
if age > 18:
print("已经成年了")
现在
if (age:= 20) > 18:
print("已经成年了")
在不使用海象运算符之前:
file = open("demo.txt", "r")
while True:
line = file.readline()
if not line:
break
print(line.strip())
有了海象运算符之后:
file = open("demo.txt", "r")
while (line := file.readline()):
print(line.strip())
列表推导式得出所有会员中过于肥胖的人的 bmi 指数
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},
]
count = 0
def get_bmi(info):
global count
count += 1
print(f"执行了 {count} 次")
height = info["height"]
weight = info["weight"]
return weight / (height**2)
# 查出所有会员中过于肥胖的人的 bmi 指数
fat_bmis = [get_bmi(m) for m in members if get_bmi(m) > 24]
print(fat_bmis)
输出如下
执行了 1 次
执行了 2 次
执行了 3 次
执行了 4 次
[25.88057063502083]
在有了海象运算符之后,就可以不用在这种场景下做出妥协
# 查出所有会员中过于肥胖的人的 bmi 指数
fat_bmis = [bmi for m in members if (bmi := get_bmi(m)) > 24]
执行了 1 次
执行了 2 次
执行了 3 次
[25.88057063502083]
参考了 https://www.cnblogs.com/wongbingming/p/12743802.html
新技能GET