gpt4 book ai didi

python - Python dict 文字会按照写入的顺序进行评估吗?

转载 作者:太空狗 更新时间:2023-10-29 17:02:57 25 4
gpt4 key购买 nike

假设我在 Python 中遇到了这样的情况:

_avg = {'total':0.0, 'count':0}    # HACK: side-effects stored here

def procedure(n):
_avg['count'] += 1
_avg['total'] += n
return n

def get_average():
return _avg['total'] / _avg['count']

my_dict = {
'key0': procedure(0),
'key2': procedure(2),
'key1': get_average()
}
assert(my_dict['key1'] == 1.0)

我知道 my_dict.keys() 的顺序是未定义的,但我想知道的是是否可以保证通过这样的文字进行初始化以特定的顺序。 my_dict['key1'] 的值是否始终如断言那样为 1.0

最佳答案

字典的求值顺序应该和写的一样,但是有个outstanding bug其中 valueskeys 之前计算。 (该错误最终在 Python 3.5 中得到修复)。

引自reference documentation :

Python evaluates expressions from left to right.

来自错误报告:

Running the following code shows "2 1 4 3", but in reference manual http://docs.python.org/reference/expressions.html#expression-lists the evaluation order described as {expr1: expr2, expr3: expr4}

def f(i):
print i
return i

{f(1):f(2), f(3):f(4)}

Guido 说:

I am sticking with my opinion from before: the code should be fixed. It doesn't look like assignment to me.

此错误已在 Python 3.5 中修复,因此在 Python 3.4 和更早版本中,值仍然在键之前计算:

>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=4, micro=2, releaselevel='final', serial=0)
>>> def f(i):
... print(i)
... return i
...
>>> {f(1):f(2), f(3):f(4)}
2
1
4
3
{1: 2, 3: 4}

由于您的代码不需要首先评估 key ,因此可以保证您的代码正常工作;即使在每个对应值之后评估键,键值对仍然按顺序评估。

关于python - Python dict 文字会按照写入的顺序进行评估吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28156687/

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