操作数是什么:=意思,更具体地说是 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,您需要知道所引用的数据结构,以及更多的算法实现。
关于伪代码的一些注意事项:
==
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
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; }
注意大括号用法和赋值运算符的区别。