一文学会为何(不)使用 Python 的海象Walrus 运算符

B站影视 2025-02-04 09:04 2

摘要:在 Python 中,如果要为表达式中的变量赋值,可以使用 Walrus 运算符 :=。虽然 x = 5 是一个简单的变量赋值,但 x := 5 是您将如何使用 Walrus 运算符。

Python 3.8 中引入的 Walrus 运算符支持在表达式内进行赋值,但需要谨慎使用以保持可读性。

在 Python 中,如果要为表达式中的变量赋值,可以使用 Walrus 运算符 :=。虽然 x = 5 是一个简单的变量赋值,但 x := 5 是您将如何使用 Walrus 运算符。

使用循环构造是很常见的,在这种构造中,读取输入以在循环中进行处理,并且循环条件取决于输入。在这种情况下,使用 walrus 运算符可以帮助保持循环更干净。

没有 Walrus 运算符

data = input("Enter your data: ")while len(data) > 0: print("You entered:", data) data = input("Enter your data: ")

当运行上述代码时,只要您输入非空字符串,系统就会反复提示您输入一个值。

请注意,存在冗余。最初读入数据变量的输入。在循环中,您打印出输入的值并再次提示用户输入。循环条件检查字符串是否为非空。

使用海象walrus运算符

可以删除冗余并使用 walrus 运算符重写上述版本。为此,可以使用 walrus 运算符读取输入并检查它是否为非空字符串(所有这些都在循环条件内),如下所示:

while (data := input("Enter your data: ")) != "": print("You entered:", data)

现在,这比第一个版本更简洁。

有时,在列表推导式中会有函数调用。如果有多个昂贵的函数调用,这可能会效率低下。在这些情况下,使用 walrus 运算符重写可能会有所帮助。

没有 海象Walrus 运算符

以下示例为例,其中在列表推导表达式中有两个对“compute_profit”函数的调用:

使用利润值填充新列表,然后检查利润值是否高于指定的阈值。# Function to compute profitdef compute_profit(sales, cost): return sales - cost# Without Walrus operatorsales_data = [(100, 70), (200, 150), (150, 100), (300, 200)]profits = [compute_profit(sales, cost) for sales, cost in sales_data if compute_profit(sales, cost) > 50]

使用海象操作符

可以将函数调用的返回值分配给“profit”变量,并使用它填充列表,如下所示:

# Function to compute profitdef compute_profit(sales, cost): return sales - cost# With Walrus Operatorsales_data = [(100, 70), (200, 150), (150, 100), (300, 200)]profits = [profit for sales, cost in sales_data if (profit := compute_profit(sales, cost)) > 50]

如果过滤条件涉及成本高昂的函数调用,则此版本更好。

现在已经看到了一些关于如何以及何时可以使用 Python 的 walrus 运算符的示例,看看一些不使用模式。

在列表推导器中使用了 walrus 运算符,以避免在前面的示例中重复调用函数。但是,过度使用海象操作员可能同样糟糕。

由于存在多个嵌套条件和赋值,以下列表推导式难以阅读。

# Function to compute profitdef compute_profit(sales, cost): return sales - cost# Messy list comprehension with nested walrus operatorsales_data = [(100, 70), (200, 150), (150, 100), (300, 200)]results = [ (sales, cost, profit, sales_ratio) for sales, cost in sales_data if (profit := compute_profit(sales, cost)) > 50 if (sales_ratio := sales / cost) > 1.5 if (profit_margin := (profit / sales)) > 0.2]

作为练习,您可以尝试将逻辑分解为单独的步骤 - 在常规循环中和 if 条件语句中。这将使代码更易于阅读和维护。

使用嵌套的 walrus 运算符可能会导致代码难以阅读和维护。当逻辑涉及单个表达式中的多个赋值和条件时,这尤其成问题。

# Example of nested walrus operators values = [5, 15, 25, 35, 45]threshold = 20results = for value in values: if (above_threshold := value > threshold) and (incremented := (new_value := value + 10) > 30): results.append(new_value)print(results)

在这个例子中,嵌套的 walrus 运算符使得理解变得困难,需要读者在一行中解开多层逻辑,从而降低了可读性。

来源:自由坦荡的湖泊AI

相关推荐