122

操作数是什么:=意思,更具体地说是 Python 的意思?

有人可以解释如何阅读这段代码吗?

node := root, cost = 0
frontier := priority queue containing node only
explored := empty set
4

5 回答 5

121

更新的答案

在问题的上下文中,我们正在处理伪代码,但从Python 3.8 开始:=实际上是一个允许在表达式中分配变量的有效运算符:

# Handle a matched regex
if (match := pattern.search(data)) is not None:
    # Do something with match

# A loop that can't be trivially rewritten using 2-arg iter()
while chunk := file.read(8192):
   process(chunk)

# Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]

# Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]

有关详细信息,请参阅PEP 572 。

原始答案

你发现的是伪代码

伪代码是对计算机程序或其他算法的操作原理的非正式高级描述。

:=实际上是赋值运算符。在 Python 中,这很简单=

要将这个伪代码翻译成 Python,您需要知道所引用的数据结构,以及更多的算法实现。

关于伪代码的一些注意事项:

  • :=是赋值运算符或=在 Python 中
  • =是相等运算符或==在 Python 中
  • 有一定的款式,你的里程可能会有所不同:

帕斯卡风格

procedure fizzbuzz
For i := 1 to 100 do
    set print_number to true;
    If i is divisible by 3 then
        print "Fizz";
        set print_number to false;
    If i is divisible by 5 then
        print "Buzz";
        set print_number to false;
    If print_number, print i;
    print a newline;
end

C风格

void function fizzbuzz
For (i = 1; i <= 100; i++) {
    set print_number to true;
    If i is divisible by 3
        print "Fizz";
        set print_number to false;
    If i is divisible by 5
        print "Buzz";
        set print_number to false;
    If print_number, print i;
    print a newline;
}

注意大括号用法和赋值运算符的区别。

于 2014-09-23T16:41:24.260 回答
88

PEP572提议支持:=Python 中的运算符以允许在表达式中进行变量赋值。

此语法在 Python 3.8 中可用。

于 2018-04-27T22:37:57.687 回答
44

问题中的代码是伪代码;那里,:=代表分配。

但是,对于未来的访问者,以下内容可能更相关:下一版本的 Python (3.8) 将获得一个新的运算符:=, 允许赋值表达式(详细信息、激励示例和讨论可以在PEP 572中找到,暂时接受2018 年 6 月下旬)。

使用这个新的运算符,您可以编写如下内容:

if (m := re.search(pat, s)):
    print m.span()
else if (m := re.search(pat2, s):
    …

while len(bytes := x.read()) > 0:
    … do something with `bytes`

[stripped for l in lines if len(stripped := l.strip()) > 0]

而不是这些:

m = re.search(pat, s)
if m:
    print m.span()
else:
    m = re.search(pat2, s)
    if m:
        …

while True:
    bytes = x.read()
    if len(bytes) <= 0:
        return
    … do something with `bytes`

[l for l in (l.stripped() for l in lines) if len(l) > 0]
于 2018-07-06T03:47:50.640 回答
20

这个符号 := 是 Python 中的赋值运算符(通常称为海象运算符)。简而言之,海象运算符会压缩我们的代码以使其更短。

这是一个非常简单的例子:

# without walrus
n = 30
if n > 10:
    print(f"{n} is greater than 10")

# with walrus
if (n := 30) > 10:
    print(f"{n} is greater than 10")

这些代码是相同的(并且输出相同的东西),但是如您所见,带有海象运算符的版本仅压缩为两行代码,以使事情更紧凑

现在,你为什么要使用海象运算符?

首先,不要觉得有义务。

我自己什至很少使用这个。我只是使用海象运算符稍微压缩我的代码,主要是在我使用正则表达式时。

您还可以找到自己的用例。重要的是您对此有一个粗略的了解,并且知道当您遇到此类问题时它可能会有所帮助。

到目前为止,这就是我如何在更高层次上解释海象算子。希望你学到了一些东西。

于 2020-09-14T00:10:00.297 回答
13

10 月 14 日快乐 3.8 发布!

有一种新的语法:=可以将值作为更大表达式的一部分分配给变量。由于它与海象的眼睛和獠牙相似,因此被亲切地称为“海象操作员”。

在此示例中,赋值表达式有助于避免调用len()两次:

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

Python 3.8 的新特性 - 赋值表达式

于 2019-10-21T14:09:29.733 回答