作者:黄小翻_618 | 来源:互联网 | 2023-05-17 18:06
这是一段代码片段.x{}x[1]len(x)printx{1:0}这个定义得很好吗?也就是说,x{1:1}可以吗?因为我记得C’98中的等效程序(如果我们使用std::map)具有
这是一段代码片段.
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 documentation和3.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:
06001
因此…
len(x)将在我们执行x [1]之前完全计算,因此x [1] == 0并且这是明确定义的.