单行 if else in python 字典理解法

single line if else in python dictionary comprehension method

我刚刚尝试了这样的列表理解

[i if i==0 else i+100 for i in range(0,3)]

它起作用了,但是当我尝试类似的字典理解时,它抛出一个错误:

d={3:3}
{d[i]:0 if i==3 else d[i]:True for i in range(0,4) }

可能是什么原因?如何使用 if else?

来理解字典?

由此产生的错误:

    {d[i]:0 if i==3 else d[i]:True for i in range(0,4) }
                             ^
SyntaxError: invalid syntax

注意:我在这里使用的例子只是一个随机的例子,而不是我的实际代码。 我可以使用替代解决方案来做到这一点,但我现在只看字典理解来学习。

您正在使用 conditional expression。它只能用在接受表达式的地方。

在字典理解中,键和值部分是 单独的 表达式,由 : 分隔(因此 : 字符是 不是表达式的一部分)。您可以在其中每一个中使用条件表达式,但不能同时对两者使用一个条件表达式。

这里只需要在数值部分使用即可:

{d[i]: 0 if i == 3 else True for i in range(4)}

但是,您会得到一个 KeyError 异常,因为 d 字典没有 012 键。

参见表达式参考文档的Dictionary displays section

dict_display       ::=  “{” [key_datum_list | dict_comprehension] “}”
[...]
dict_comprehension ::=  expression “:” expression comp_for

[...]

A dict comprehension, in contrast to list and set comprehensions, needs two expressions separated with a colon followed by the usual “for” and “if” clauses.

dict comprehension with if-else 问题的另一种解决方案:

dict((x, x ** 2) if x > 0 else (x, -x ** 2) for x in range(-4, 5))