本文介绍了Python:if / else in dict的理解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python2.7 +存在任何方式来做如下:

In python2.7+ exist any way to make something like:

{ 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如果测试其他B 是一个有效的python表达式。你的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.

这篇关于Python:if / else in dict的理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 07:57