gpt4 book ai didi

python - 冒号等于什么(:=) in Python mean?

转载 作者:IT老高 更新时间:2023-10-28 20:29:51 33 4
gpt4 key购买 nike

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

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

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

最佳答案

更新答案

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

Pseudocode is an informal high-level description of the operating principle of a computer program or other algorithm.

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

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

关于python - 冒号等于什么(:=) in Python mean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26000198/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com