2015-11-21 154 views
0
def sumColumns(filename): 
    from csv import DictReader 
    with open(filename) as f: 
     a1=[row["bob"] for row in DictReader(f)] # I want this part to extract every 
     a2=[row["anna"] for row in DictReader(f)]# column into a list and be put into 
     a3=[row["tim"] for row in DictReader(f)] # variables. It only works for a1. 
     dic={} 
     total1=0 
     total2=0 
     total3=0 
     for i in a1: 
      total1 = total1 + float(i) 
     dic["bob"] = total1 # adding the name of the person with the number into a dict 
     for i in a2: 
      total2 = total2 + float(i) 
     dic["anna"] = total2 
     for i in a3: 
      total3 = total3 + float(i) 
     dic["tim"] = total3 
     return dic 

我的問題是,此代碼僅適用於「a1」變量,其他2個返回0,所以我的最終結果是{'bob': 41.0, 'anna': 0, 'tim':0}Dictreader未按預期工作

我不知道如何解決這個問題。在此之前,我嘗試了zip()函數,但是它一直返回一個錯誤。

這裏的csv文件對於要下載的人:

http://tempsend.com/0D1ED483C3

而對於任何人,不喜歡在這裏下載文件是它的外觀圖片:

Image of csv file

回答

1

您正嘗試從同一個文件重新讀取,但忘記將文件倒帶。文件有當前文件位置,當您從文件中讀取時,它是高級的;在到達結尾後嘗試讀取則導致根本沒有數據被讀取。

你可以重新風檔倉位的每次用f.seek(0)開始,而不是從文件中讀取3次,你應該閱讀一次和重用的信息:

with open(filename) as f: 
    rows = list(DictReader(f)) 
    a1 = [row["bob"] for row in rows] 
    a2 = [row["anna"] for row in rows] 
    a3 = [row["tim"] for row in rows] 

你可以只需使用sum()功能在這裏:

with open(filename) as f: 
    rows = list(DictReader(f)) 
    dic['bob'] = sum(float(r['bob']) for r in rows) 
    dic['anna'] = sum(float(r['anna']) for r in rows) 
    dic['tim'] = sum(float(r['tim']) for r in rows) 

,或者使用與名稱的循環:

with open(filename) as f: 
    rows = list(DictReader(f)) 
    for name in ('bob', 'anna', 'tim'): 
     dic[name] = sum(float(r[name]) for r in rows) 
+0

謝謝!這似乎解決了它! – Matic