gpt4 book ai didi

Python类: Lambda Name Error - Name not defined

转载 作者:行者123 更新时间:2023-11-30 22:37:35 26 4
gpt4 key购买 nike

我是 Python 3.6 的初学者。我正在尝试创建一个名为“Week”的类,它将执行某些操作并最终打印变量“avg_mon”的值。

为了计算“avg_mon”的值,我使用了匿名函数“lambda”。

from datetime import datetime
from datetime import date
from operator import add
from operator import itemgetter

class Week():
blank_mon=[0]*24
sum_mon=blank_mon
count_mon=0

print ("Blank Monday: ",blank_mon)
#curr_mon=[1,0,2,0,3,0,4,0,5,0,3,0,3,0,2,0,1,0,2,0,1,0,1,0]
curr_mon=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
print ("Current Monday",curr_mon)
count_mon = count_mon + 1
print ("Monday Count:",count_mon)
sum_mon=list(map(add,sum_mon,curr_mon)) #Adds all the Mondays together for each hour
print ("Total sum of all Mondays::",sum_mon)
avg_mon = list(map(lambda w_mon: float(w_mon)/count_mon,sum_mon)) #Gets the average of the Mondays for each hour
print ("Average Monday::",avg_mon)


mon = Week()

当我执行代码时,出现以下错误。我在代码中没有看到任何拼写/命名错误。我无法弄清楚这种错误背后的原因。

Blank Monday:  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Current Monday [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
Monday Count: 1
Total sum of all Mondays:: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
Traceback (most recent call last):
File "C:\Users\Admin\Documents\GitHub\Doze\functest.py", line 27, in <module>
class Week():
File "C:\Users\Admin\Documents\GitHub\Doze\functest.py", line 40, in Week
avg_mon = list(map(lambda w_mon: float(w_mon)/count_mon,sum_mon)) #Gets the average of the Mondays for each hour
File "C:\Users\Admin\Documents\GitHub\Doze\functest.py", line 40, in <lambda>
avg_mon = list(map(lambda w_mon: float(w_mon)/count_mon,sum_mon)) #Gets the average of the Mondays for each hour
NameError: name 'count_mon' is not defined

最佳答案

您可能想将其中一些代码放入构造函数中。正如所写,它全部定义为类的一部分,这导致了您的问题:调用 lambda 函数时,count_mon 不在范围内。

将此代码移至 __init__ 函数内:

class Week(): 
def __init__(self):
blank_mon=[0]*24
sum_mon=blank_mon
count_mon=0

print ("Blank Monday: ",blank_mon)
#curr_mon=[1,0,2,0,3,0,4,0,5,0,3,0,3,0,2,0,1,0,2,0,1,0,1,0]
curr_mon=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
print ("Current Monday",curr_mon)
count_mon = count_mon + 1
print ("Monday Count:",count_mon)
sum_mon=list(map(add,sum_mon,curr_mon)) #Adds all the Mondays together for each hour
print ("Total sum of all Mondays::",sum_mon)
avg_mon = list(map(lambda w_mon: float(w_mon)/count_mon,sum_mon)) #Gets the average of the Mondays for each hour
print ("Average Monday::",avg_mon)

以下是发生这种情况的完整解释:Accessing class variables from a list comprehension in the class definition

关于Python类: Lambda Name Error - Name not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43840250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com