字典推导中的海象操作符



我想避免在字典推导中对平均值进行双重求值,我尝试使用海象运算符:

>>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]}
>>> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}

,但这给了我以下错误:

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}
File "<pyshell#2>", line 1, in <dictcomp>
q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}
NameError: name 'mean' is not defined

这个错误只在我尝试使用变量时发生,在定义它时没有问题:

>>> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if (sum(dic[x]) // len(dic[x])) > 65}
>>> mean
86
>>> q
{'B': 77, 'C': 87, 'D': 86}

为什么?我哪里说错了?

您的代码大致相当于

q = {}
for x in dic:
if mean > 65:
mean := ...
q[x] = mean

这意味着你在分配mean之前使用它。

你需要定义移动到if-clause-section dict-comprehension。

>>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]}
>>> q = {x: mean for x in dic if (mean := (sum(dic[x]) // len(dic[x]))) > 65}
>>> q
{'B': 77, 'C': 87, 'D': 86}

转换成

q = {}
for x in dic:
if (mean := ...) > 65:
q[x] = mean

需要将赋值表达式放在推导式的条件中,而不是放在字典的值组件中:

dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]}
q = {x:mean for x in dic if (mean := (sum(dic[x]) // len(dic[x]))) > 65}

输出:

{'B': 77, 'C': 87, 'D': 86}

相关内容

  • 没有找到相关文章

最新更新