Python海象运算符超详细讲解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python海象运算符超详细讲解

小嗷犬   2023-02-03 我要评论

介绍

海象运算符,即 := ,在 PEP 572 中被提出,并在 Python3.8 版本中发布。

海象运算符的英文原名叫Assignment Expresions,即赋值表达式。

它由一个冒号:和一个等号=组成,即:=。而它被称作walrus operator(海象运算符),是因为它长得像一只海象。

语法

海象运算符的语法格式如下:

variable_name := expression

它的作用是将表达式的值赋值给变量,然后返回表达式的值。

而传统的赋值运算符=在赋值之后,返回的是None

用法

海象运算符返回的是表达式的值,而不是None,因此可以用于一些需要表达式的地方。

if 语句

使用海象运算符:

if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

传统写法:

n = len(a)
if n > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

while 循环

while 循环逐行读取文件

使用海象运算符:

while (line := f.readline()) != "":
    print(line, end="")

传统写法:

line = f.readline()
while line != "":
    print(line, end="")
    line = f.readline()

while 循环验证输入

使用海象运算符:

while (user_input := input("Enter something: ")) != "quit":
    print(f"You entered {user_input}")

传统写法:

user_input = input("Enter something: ")
while user_input != "quit":
    print(f"You entered {user_input}")
    user_input = input("Enter something: ")

推导式

使用海象运算符:

nums = [18, 29, 31, 37, 41, 59, 61, 73, 79, 83, 97]
cnt = 0
def f(x):
    global cnt
    cnt += 1
    return int(x ** 0.5)
print([y for x in nums if (y := f(x)) > 7])
print(cnt)
# 输出:
# [8, 8, 9, 9]
# 11

传统写法:

nums = [18, 29, 31, 37, 41, 59, 61, 73, 79, 83, 97]
cnt = 0
def f(x):
    global cnt
    cnt += 1
    return int(x ** 0.5)
print([f(x) for x in nums if f(x) > 7])
print(cnt)
# 输出:
# [8, 8, 9, 9]
# 15

可以看出,在上面那种情况下,使用海象运算符可以减少函数的调用次数。

当数据量大时,这种差别就会更加明显。

三元表达式

使用海象运算符:

money, spend = 2000, 1500
print(f"你还有{money}元" if (money := money - spend) > 1000 else "你只有{money}元了")

传统写法:

money, spend = 2000, 1500
money = money - spend
print(f"你还有{money}元" if money > 1000 else f"你只有{money}元了")

总结

综上所述,海象运算符可以用于一些需要表达式的地方,比如if语句、while循环、推导式、三元表达式等。

它一定程度上减少了代码的行数,使代码更加简洁,甚至在某些情况下可以提高程序的效率;但通常情况下,使用海象运算符会降低代码的可读性,使代码更难以理解。

因此,使用海象运算符时,应该考虑清楚,是否真的需要使用它。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们