[英]Python Class: Lambda Name Error - Name not defined
我是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
您可能希望將一些此代碼放入構造函數中。 如上所述,它都被定義為類的一部分,這會導致您的問題: count_mon
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)
以下是為什么會發生這種情況的完整解釋: 從類定義中的列表解析中訪問類變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.