【问题标题】:What does colon equal (:=) in Python mean?Python中的冒号等于(:=)是什么意思?
【发布时间】:2014-11-17 23:03:38
【问题描述】:

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

谁能解释一下如何阅读这段代码?

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

【问题讨论】:

  • 我的猜测是,这是来自此 wiki article 的伪代码,并且可能 OP 正在询问如何在 Python 中解释此代码(这是一个作业)

标签: python colon-equals


【解决方案1】:

更新答案

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

原答案

你找到的是pseudocode

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

:= 实际上是赋值运算符。在 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;
}

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

【讨论】:

    【解决方案2】:

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

    此语法在 Python 3.8 中可用。

    【讨论】:

    • @z33k 这个问题是在 PEP 创建多年前提出的。这当然不能回答问题。虽然可能是评论......
    • @MaxRied 我刚刚通过谷歌找到了这个答案,这正是我想要的。即使在提出问题时它并不相关,但现在肯定是。
    • PEP572 允许 Python 拥有该运算符允许人们在 C 中拥有的所有令人讨厌的错误。
    • @vy32。你允许一个有能力的用户做的越多,你允许每个人引入的 bug 就越多。这不是限制的理由,如果这就是你的意思。
    • @MadPhysicist - 我并不是暗示不应将此运算符添加到 Python 3.8。我只是指出这将是一个新的错误来源,并指出 C 中的 = 赋值运算符有着漫长而麻烦的历史。
    【解决方案3】:

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

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

    【讨论】:

    • PEP 577 与 PEP 572 竞争。
    • 是的;它已被其作者撤回。
    • 哦,你是对的。这太糟糕了。我更喜欢 577。
    【解决方案4】:

    10 月 14 日 3.8 发布快乐!

    新语法:= 将值分配给变量作为更大表达式的一部分。因其酷似海象的眼睛和獠牙,被亲切地称为“海象操作员”。

    在本例中,赋值表达式有助于避免两次调用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

    【讨论】:

    • 时间当然是箭
    【解决方案5】:

    这个符号 := 是 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")
    

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

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

    首先,不要觉得有义务。

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-09-25
      • 2012-10-09
      • 2020-05-21
      • 1970-01-01
      • 2019-09-14
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多