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

2024-06-02 08:41:17 发布

您现在位置:Python中文网/ 问答频道 /正文

对于Python来说,:=操作数意味着什么?

有人能解释一下如何阅读这段代码吗?

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

Tags: 代码nodeonlyqueuerootemptyfrontierpriority
3条回答

PEP572建议在Python中支持:=运算符,以允许在表达式中分配变量。

此语法将在Python3.8中提供。

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

不过,对于未来的访问者来说,以下内容可能更为相关:下一版本的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]

您发现的是伪代码

http://en.wikipedia.org/wiki/Pseudocode

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

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

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

关于psuedocode的一些注记

:=是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;
}

注意大括号用法和赋值运算符的不同。

相关问题 更多 >