gpt4 book ai didi

python - 如何在 dict 创建期间从另一个 dict 构建 Python dict 值?

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:28 27 4
gpt4 key购买 nike

我想构建一个字典,其中一个值是从另一个值构建的。

我想写

d = {
'a':1,
'b':self['a']+1
}

但它没有按预期工作:

>>> {'a':1, 'b':self['a']+1}
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'self' is not defined

那么,我怎样才能实现这个 Python 技巧呢? (我使用的是 Python2.4)

最佳答案

您不能引用尚未创建的词典。只需在创建字典后分配额外的键:

d = {'a': 1}
d['b'] = d['a'] + 1

或者,首先将值设置为单独的变量,然后创建字典:

a_value = 1
d = {'a': a_value, 'b': a_value + 1}

关于python - 如何在 dict 创建期间从另一个 dict 构建 Python dict 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37028334/

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