简体   繁体   English

Python条件字典理解

[英]Python conditional dictionary comprehension

Is there a reason why this list comp works: 此列表组合有效的原因是什么:

N = 5
d = {0:100, 2:5}
[(dpidx,d[dpidx]) if dpidx in d else (dpidx,dpidx) for dpidx in range(N)]

[(0, 100), (1, 1), (2, 5), (3, 3), (4, 4)]

but this dict comp doesn't work? 但是这个字典补偿不起作用吗? :

{dpidx:d[dpidx] if dpidx in d else dpidx:dpidx for dpidx in range(N)}

{dpidx:d[dpidx] if dpidx in d else dpidx:dpidx for dpidx in range(N)}
                                        ^
SyntaxError: invalid syntax

I'm looking for: 我在找:

{0: 100, 1: 1, 2: 5, 3: 3, 4: 4}

I thought I could just use a dict comp instead of a dict(list comp). 我以为我可以只用dict comp代替dict(list comp)。

Thanks in advance! 提前致谢!

You cannot repeat the key. 您无法重复输入密钥。 A dictionary comprehension has the form 字典理解具有以下形式

{k: v for ...}

where k and v are expressions. 其中kv是表达式。 One (or both) of these expressions can be a conditional expression, which will give 这些表达式中的一个(或两个)可以是条件表达式,

{dpidx:d[dpidx] if dpidx in d else dpidx for dpidx in range(N)}

But k: v is not an expression in its own right. 但是k: v本身并不是一个表达。

An easier way to write this is 一个更简单的方法是

{dpidx:d.get(dpidx, dpidx) for dpidx in range(N)}

You need to change dpidx:dpidx to just dpidx 您需要将dpidx:dpidx更改为仅dpidx

Remember "d[dpidx] if dpidx in d else dpidx" means the value in the dictionary if there, otherwise the value of dpidx", it doesn't make sense having "otherwise the value of dpidx:dpidx" 请记住,“ d [dpidx],如果dpidx在d或dpidx中”则表示字典中的值(否则为dpidx的值),而“否则为dpidx:dpidx的值”没有意义。

d={1:2,3:5}
N=5

g={dpidx: d[dpidx] if dpidx in d else dpidx for dpidx in range(N)}

print g
>>>
{0: 0, 1: 2, 2: 2, 3: 5, 4: 4}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM