Python中的简单语法错误(如果不执行dict理解) [英] Simple syntax error in Python if else dict comprehension
问题描述
我有一个集合和一个字典,值= 5
I have a set and dictionary and a value = 5
v = s = {'a', 'b', 'c'}
d = {'b':5 //<--new value}
例如,如果字典d中的键"b"在集合s中,那么我想在返回字典推导时使该值等于新值;如果集合s中的键不在字典d中,则我希望使该值等于新值.所以这是我的代码,其中s ['b'] = 5并且我的新字典是...
If the key 'b' in dictionary d for example is in set s then I want to make that value equal to the new value when I return a dict comprehension or 0 if the key in set s is not in the dictionary d. So this is my code to do it where s['b'] = 5 and my new dictionary is is ...
{'a':0, 'b':5, 'c':0}
我写了一个dict理解
I wrote a dict comprehension
{ k:d[k] if k in d else k:0 for k in s}
^
SyntaxError: invalid syntax
为什么?!我太生气了,它不起作用.如果python中没有其他方法,这是怎么做的?
Why?! Im so furious it doesnt work. This is how you do if else in python isnt it??
对不起大家.对于那些访问过此页面的人,我最初输入{k:d [k],如果v中的k,否则k:0表示v中的k},而s ['b'] = 5只是我创建的新字典的一种表示形式键"b"等于5,但这不是正确的说法,您不能像这样迭代一个集合.
So sorry everyone. For those who visited this page I originally put { k:d[k] if k in v else k:0 for k in v} and s['b'] = 5 was just a representation that the new dictionary i created would have a key 'b' equaling 5, but it isnt correct cus you cant iterate a set like that.
因此重申v和s相等.它们只是矢量和集合.
So to reiterate v and s are equal. They just mean vector and set.
推荐答案
您要实现的扩展形式是
a = {}
for k in v:
a[k] = d[k] if k in d else 0
where d[k] if k in d else 0
is the Python's version of ternary operator. See? You need to drop k:
from the right part of the expression:
{k: d[k] if k in d else 0 for k in v} # ≡ {k: (d[k] if k in d else 0) for k in v}
您可以像这样写得简洁
a = {k: d.get(k, 0) for k in d}
这篇关于Python中的简单语法错误(如果不执行dict理解)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!