更新答案
在问题的上下文中,我们正在处理伪代码,但是从 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 572更多细节。
原答案
你发现的是伪代码
伪代码是操作的非正式高级描述
计算机程序或其他算法的原理。
:=
实际上是赋值运算符。在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-style
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;
}
请注意大括号用法和赋值运算符的差异。