从 Dicts 获取值时的 Python If then Else 样式
我经常为下面的 if/else 语法而苦苦挣扎,我希望有人能给我一些他们认为更清楚的意见,或者这是否违反了任何 Pythonism(我已经搜索过,但找不到任何东西) )。
其中之一更好还是对/错?
value = None
if 'value' in some_dict:
value = some_dict['value']
some_func(value=value)
或:
if 'value' in some_dict:
value = some_dict['value']
else:
value = None
some_func(value=value)
或:
some_func(value=some_dict.get('value', None))
我可以看到所有的原因。
I often struggle with the following if/else syntax and I was hoping some people could give me some of their opinions as to what they think is more clear or if this violates any Pythonisms (I've searched and wasn't able to find anything).
Is one of these better and or right/wrong?
value = None
if 'value' in some_dict:
value = some_dict['value']
some_func(value=value)
OR:
if 'value' in some_dict:
value = some_dict['value']
else:
value = None
some_func(value=value)
OR:
some_func(value=some_dict.get('value', None))
I could see reasons for all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当然,最后一种是最好的 - 所描述的情况正是 dict.get 的情况。
请注意 -
get
的第二个参数是多余的,您可以简单地编写:Of course the last one is the best - described situation is exact case for
dict.get
.Just a note - second parameter to
get
is superfluous, you can simply write:这对我来说看起来最自然:
或者:最后一种情况。我回答时问题已被编辑。
This looks most natural to me:
Or: the last case. The question was edited while I replied.
使用字典的
get()
方法,如第三个示例中所示。该用例正是之前的情况。Use the dict's
get()
method as in your third example. That use case is exactly what it's there fore.这只是一个风格问题,我会使用最后一个,因为它更简洁(注意你可以省略
None
因为它是默认值)顺便说一句,还有这个:
但这正是
.get()
确实this is just a matter of style, I would use the last just because it's more succint (and notice you can omit the
None
as it is the default)btw there's also this:
but that's exactly what
.get()
does正如其他人所说, dict.get() 方法似乎是越适合您的需要。
但是,如果您不想在该值不在字典中的情况下启动该方法,则可以使用 pythonic 方式(根据 EAFP 原则)将是:
As the others said, the dict.get() method seems to be the more suitable to what you need.
BUT, if you didn't want to launch the method if the value wasn't in the dictionnary, a pythonic way (according to the EAFP principle) would have been :