Skip to main content
 首页 » 编程设计

python之python字典理解方法中的单行if else

2025年05月04日15lhb25

我刚刚试过这样的列表理解

[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字典没有0, 1,和 2 键。

参见 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.