Python 中的冒号等于 (:=) 是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26000198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:55:42  来源:igfitidea点击:

What does colon equal (:=) in Python mean?

pythoncolon-equals

提问by Julio

What does the :=operand mean, more specifically for Python?

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

Can someone explain how to read this snippet of code?

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

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

采纳答案by Mike McMahon

Updated answer

更新答案

In the context of the question, we are dealing with pseudocode, but starting in Python 3.8, :=is actually a valid operator that allows for assignment of variables within expressions:

在问题的上下文中,我们正在处理伪代码,但从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]

See PEP 572for more details.

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

Original Answer

原答案

What you have found is pseudocode

你发现的是伪代码

Pseudocodeis an informal high-level description of the operating principle of a computer program or other algorithm.

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

:=is actually the assignment operator. In Python this is simply =.

:=实际上是赋值运算符。在 Python 中,这只是=.

To translate this pseudocode into Python you would need to know the data structures being referenced, and a bit more of the algorithm implementation.

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

Some notes about psuedocode:

关于伪代码的一些说明:

  • :=is the assignment operator or =in Python
  • =is the equality operator or ==in Python
  • There are certain styles, and your mileage may vary:
  • :=是赋值运算符还是=在 Python 中
  • =是相等运算符还是==在 Python 中
  • 有某些款式,您的里程可能会有所不同:

Pascal-style

帕斯卡式

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-style

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;
}

Note the differences in brace usage and assignment operator.

请注意大括号用法和赋值运算符的差异。

回答by chadlagore

PEP572proposed support for the :=operator in Python to allow variable assignments within expressions.

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

This syntax is available in Python 3.8.

此语法在 Python 3.8 中可用。

回答by Clément

The code in the question is pseudo-code; there, :=represents assignment.

问题中的代码是伪代码;在那里,:=代表赋值。

For future visitors, though, the following might be more relevant: the next version of Python (3.8) will gain a new operator, :=, allowing assignment expressions(details, motivating examples, and discussion can be found in PEP 572, which was provisionally accepted in late June 2018).

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

With this new operator, you can write things like these:

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

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]

instead of these:

而不是这些:

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]

回答by Wera

Happy 3.8 Release on 14th of October!

10 月 14 日 3.8 发布快乐!

There is new syntax :=that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.

In this example, the assignment expression helps avoid calling len()twice:

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

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

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

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

What's New In Python 3.8 - Assignment expressions

Python 3.8 新特性 - 赋值表达式