gpt4 book ai didi

python - 从可能丢失的 dict 值初始化 Python 变量

转载 作者:太空宇宙 更新时间:2023-11-04 06:47:52 25 4
gpt4 key购买 nike

执行此操作的 Pythonic 方法是什么?

value = (mydict.has_key('index') and mydict['index']) or 1024

从字典的值(如果存在)初始化,否则使用默认值。

在 LBYL 和 EAFP 上得到了一些答案,但是代码太冗长了:p

我想要一些单行初始化。

PS:仅适用于 python-2.4(运行 CentOS5)

最佳答案

value = mydict.get('index', 1024)

(请注意,这并不完全等同于您的代码,因为只有当键 index 不存在时,它才会使用 1024,而您的代码也使用 1024 当键 index 对应的值是 falsy 时。从你的解释我推断前者是你真正想要的。)

关于python - 从可能丢失的 dict 值初始化 Python 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6181532/

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