字典理解中的海象运算符

walrus operator in dict comprehension

我想避免在字典理解中对均值进行双重计算,我尝试使用海象运算符:

>>> 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}

为什么?我哪里弄错了?

您需要将赋值表达式放在理解的条件中,而不是字典的值部分:

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}

您的代码大致等同于

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

这意味着您在分配之前使用 mean

您需要将定义移动到 dict-comprehension 的 if-clause-section。

>>> 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