gpt4 book ai didi

python - 代码风格——for with if

转载 作者:太空狗 更新时间:2023-10-30 00:49:19 25 4
gpt4 key购买 nike

您认为这三种编码风格中哪种更好,或者更具可读性? foo 应该对两个词典中的项目运行,但 mydict2 可以是 None

选项 1:

for a,b in mydict1.items():
foo(a,b)
if mydict2:
for a,b in mydict2.items():
foo(a,b)

选项 2:

for a,b in mydict1.items():
foo(a,b)
for a,b in mydict2.items() if mydict2 else dict().items():
foo(a,b)

选项 3:

for a,b in chain(mydict1.items(), mydict2.items() if mydict2 else dict().items()):
foo(a,b)

最佳答案

尽早检测边例,并用空字典替换它 - 这是 null object pattern :

if mydict2 is None:
mydict2 = {}

这与用于避免可变默认参数的常见模式相同。然后你总是可以有一个(非常简单的)循环:

for a, b in chain(mydict.items(), mydict2.items()):

如果您控制相关代码,请考虑更改内容,使 mydict2 一开始就不能是 None

关于python - 代码风格——for with if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31021423/

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