Jul*_*lio 24 python colon-equals
:=操作数意味着什么,更具体地说是Python?
有人可以解释如何阅读这段代码吗?
node := root, cost = 0
frontier := priority queue containing node only
explored := empty set
Run Code Online (Sandbox Code Playgroud)
Clé*_*ent 25
问题中的代码是伪代码; 在那里,:=代表任务.
对于未来的游客,不过,下面可能更重要: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]
Run Code Online (Sandbox Code Playgroud)
而不是这些:
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]
Run Code Online (Sandbox Code Playgroud)
小智 13
10 月 14 日 3.8 发布快乐!
有新的语法
:=可以将值分配给变量作为更大表达式的一部分。由于它与海象的眼睛和象牙相似,因此被亲切地称为“海象操作员”。在这个例子中,赋值表达式有助于避免调用
len()两次:Run Code Online (Sandbox Code Playgroud)if (n := len(a)) > 10: print(f"List is too long ({n} elements, expected <= 10)")
men*_*des 13
这个符号 := 是 Python 中的赋值运算符(通常称为 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")
Run Code Online (Sandbox Code Playgroud)
这些代码是相同的(并且输出相同的东西),但是正如你所看到的,带有 walrus 运算符的版本被压缩成两行代码,使事情更加紧凑
现在,为什么要使用海象运算符?
首先,不要觉得有义务。
我自己甚至很少使用这个。我只是使用 walrus 运算符来稍微压缩我的代码,主要是在我使用正则表达式时。
您还可以找到您自己的用例。重要的是您对此有一个粗略的想法,并且知道在遇到此类问题时它何时可能会有所帮助。
到目前为止,我如何在更高的层次上解释海象算子。希望你学到了一些东西。
Moh*_*med 12
:=也称为海象运算符。我们可以使用这个海象运算符来赋值并同时进行条件检查。
例如:
没有海象操作员:
a = 10
if a == 10:
print("yes")
Run Code Online (Sandbox Code Playgroud)
与海象操作员一起:
if (a := 10) == 10:
print("Yes")
Run Code Online (Sandbox Code Playgroud)
因此,我们a不仅可以在语句中使用变量,也可以在之后使用变量。它只会将新值分配给变量并启用条件检查。
Mik*_*hon 11
你发现的是伪代码
http://en.wikipedia.org/wiki/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
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
请注意大括号使用和赋值运算符的差异.
| 归档时间: |
|
| 查看次数: |
16411 次 |
| 最近记录: |