对Python更具体地说,:=操作数是什么意思?
有人能解释一下如何阅读这段代码吗?
node := root, cost = 0
frontier := priority queue containing node only
explored := empty set
对Python更具体地说,:=操作数是什么意思?
有人能解释一下如何阅读这段代码吗?
node := root, cost = 0
frontier := priority queue containing node only
explored := empty set
更新后的答案
在这个问题的上下文中,我们处理的是伪代码,但从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中的相等运算符或== 有一定的风格,你的里程可能会有所不同:
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风格的
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;
}
注意大括号用法和赋值运算符的区别。
问题中的代码是伪代码;这里,:=表示赋值。
不过,对于未来的访问者来说,以下内容可能更相关:Python(3.8)的下一个版本将获得一个新的操作符:=,允许赋值表达式(详细信息、激励示例和讨论可以在PEP 572中找到,该版本于2018年6月下旬临时接受)。
使用这个new操作符,你可以这样写:
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]
10月14日愉快的3.8发布!
新的语法:=将值赋给变量作为更大表达式的一部分。它被亲切地称为“海象操作员”,因为它与海象的眼睛和象牙相似。 在这个例子中,赋值表达式有助于避免两次调用len(): 如果(n:= len(a)) > 10: print(f"列表太长({n}个元素,期望<= 10)")
Python 3.8新增功能-赋值表达式
符号:=是Python中的赋值操作符(通常称为Walrus操作符)。简单地说,walrus操作符压缩了我们的代码,使其更短一些。
这里有一个非常简单的例子:
# 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操作符的版本被压缩为两行代码,以使内容更加紧凑。
为什么要用海象运算符呢?
首先,不要觉得有义务。
我自己甚至很少使用这个。我只是使用walrus操作符来压缩我的代码,主要是在我使用正则表达式时。
您还可以找到自己的用例。重要的是你对它有一个大概的想法,并且知道当你遇到这样的问题时它什么时候可能会有所帮助。
这是到目前为止我如何在更高的层次上解释海象算子。希望你学到了一些东西。
:=也被称为海象运算符。 我们可以使用这个海象操作符来赋值,同时进行条件检查。
Eg:
没有海象操作员:
a = 10
if a == 10:
print("yes")
与Walrus操作员:
if (a := 10) == 10:
print("Yes")
因此,我们可以在语句中使用变量a。它将简单地将新值赋给变量并启用条件检查。