2016-11-16 50 views
0

我需要訪問data_listget_data_list函數中新增的信息,第二個函數是get_month_averages,但是當我嘗試這樣做時,它說data_list未定義。我該怎麼做呢?如何訪問此列表的內容? (Python)

import csv 

def get_data_list(data_file): 
    data_file = open("table.csv", "r") 
    data_list = [] 
    for line_str in data_file: 
     data_list.append(line_str.strip().split(',')) 
    return data_list 

def get_month_averages(data_list): 
    date_list = [] 
    vol_list = [] 
    adjclos_list = [] 
    for row in data_list: 
     date_list.append(row[0]) 
     vol_list.append(row[5]) 
     adjclos_list.append(row[6]) 
     all_list = [date_list, vol_list, adjclos_list] 
    return all_list 
print (get_month_averages(data_list)) 
+2

它抱怨底部'print'線,因爲當您將它傳遞給'get_month averages'從來沒有定義'data_list'。你需要一行代碼(在函數之外),比如'data_list = get_data_list()'。你的函數的第一行也應該是'def get_data_list():',因爲它不需要參數。 – mitoRibo

回答

0

這一個工程:

import csv 

def get_data_list(): 
    data_file = open("table.csv", "r") 
    data_list = [] 
    for line_str in data_file: 
     data_list.append(line_str.strip().split(',')) 
    return data_list 

def get_month_averages(data_list): 
    date_list = [] 
    vol_list = [] 
    adjclos_list = [] 
    for row in data_list: 
     date_list.append(row[0]) 
     vol_list.append(row[5]) 
     adjclos_list.append(row[6]) 
     all_list = [date_list, vol_list, adjclos_list] 
    return all_list 

dList = get_data_list() 
mAvg = get_month_averages(dList) 
print mAvg