如何在字典理解中使用 if/else? [英] How can I use if/else in a dictionary comprehension?
本文介绍了如何在字典理解中使用 if/else?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 2.7+ 中是否存在一种方法来制作如下所示的内容?
Does there exist a way in Python 2.7+ to make something like the following?
{ something_if_true if condition else something_if_false for key, value in dict_.items() }
我知道你可以用'if'做任何事情:
I know you can make anything with just 'if':
{ something_if_true for key, value in dict_.items() if condition}
推荐答案
你已经明白了:A if test else B
是一个有效的 Python 表达式.如图所示,您的 dict 理解的唯一问题是 dict 理解中表达式的位置必须有两个表达式,用冒号分隔:
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
最后的 if
子句充当过滤器,这与具有条件表达式不同.
The final if
clause acts as a filter, which is different from having the conditional expression.
这篇关于如何在字典理解中使用 if/else?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文