gpt4 book ai didi

python - 赋值的右侧总是在赋值之前求值吗?

转载 作者:太空宇宙 更新时间:2023-11-03 12:59:38 25 4
gpt4 key购买 nike

这是一个代码片段。

x = {}
x[1] = len(x)

print x
{1: 0}

这个定义好吗?也就是说,可以 x == {1: 1} 代替吗?

因为我记得 C++ '98 中的等效程序(如果我们使用 std::map)具有未定义的行为。使用 VS 编译器和 G++ 编译时程序的输出是不同的。

最佳答案

正如我在评论中提到的,这个测试用例可以简化为:

x = {}
x[1] = len(x)

那么问题就变成了,是x[1] == 0,还是x[1] == 1

我们看看相关的2.x documentation3.x documentation :

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:

expr3, expr4 = expr1, expr2

因此...

len(x) 将在我们执行 x[1] 之前被完全计算,所以 x[1] == 0 和这个定义明确。

关于python - 赋值的右侧总是在赋值之前求值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27112647/

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