我有两个功能。第一个函数 - def training_list()创建了两个列表 - under_50k& over_50k。我想第二个函数def sums_lists()创建一个sum_list,它将两个列表中的每个索引相加,然后附加每个列表以创建1个列表 - sums_list。当我运行代码时,它表示在sums_list函数中没有定义over_50k。你能告诉我我是如何定义的吗,我想继续讨论under_50k& over_50k列表进入新功能
错误消息
File "C:\Python34\Lib\assign1.py", line 208, in sums_list over_50k_sum_list = [sum(k) for k in zip(*over_50k)] NameError: name 'over_50k' is not defined
def training_list():
data_list = create_data(data_url)
training_list = data_list[:int(len(data_list) * 75 / 100)]
test_list = data_list[int(len(data_list) * 25 / 100):]
#return training_list
over_50k = []
over_50k_count = 0
under_50k = []
under_50k_count = 0
for row in training_list:
if row[-1].lstrip() == '<=50K':
under_50k.append(row[:-1])
under_50k_count +=1
elif row [-1].lstrip() == ">50K":
over_50k.append(row[:-1])
over_50k_count +=1
return under_50k,over_50k
def sums_list():
over_50k_sum_list = []
under_50k_sum_list = []
over_50k_sum_list = [sum(k) for k in zip(*over_50k)]
under_50k_sum_list = [sum(k) for k in zip(*under_50k)]
sums_list = over_50k_sum_list + under_50k_sum_list
print(sums_list)
return sums_list
def main():
def trainging_list():
over_50k = [[1, 2, 3, 4], [3, 4, 5, 6], [7, 8, 9, 8]]
under_50k = [[1, 4, 6, 8], [3, 7, 4, 5], [6, 9, 4, 5]]
print(over_50k)
return over_50k, under_50k
over_50k, under_50k = trainging_list()
def sum_columns(over_50k, under_50k):
print("a")
over_50k_sum_list = [sum(k) for k in zip(*over_50k)]
under_50k_sum_list = [sum(k) for k in zip(*under_50k)]
sums = over_50k_sum_list + under_50k_sum_list
print(sums)
return sums
main()
答案 0 :(得分:0)
under_50k和over_50k。调用第二个函数时,需要调用该函数以使它们存在。添加:
under_50k, over_50k = training_list()
在你的第一个函数工作之后,因为它们已被指定为全局变量。
您还可以在定义第二个函数时添加参数,然后在调用它时将其读入。
def sums_list(under_50k, over_50k):
# rest of the function
然后在缩进的空间中调用一个函数,然后调用另一个函数:
p, q = training_list
sums_list(p ,q)
答案 1 :(得分:0)
您的主程序需要调用training_list
,存储返回的值,并将其传递给sums_list
。
def main():
under_50k, over_50k = training_list()
sums = sums_list(under_50k, over_50k)
但将sums_list
简化为
def sum_columns(table):
return [sum(column) for column in zip(*table)]
并使用sum_columns(under_50k + over_50k)
进行调用。 (我更喜欢名称sum_columns
,因为它更容易理解它正在做什么。)