2015-12-09 99 views
1

我需要一個總和函數的幫助。我試圖在文檔中找到前綴爲「X-DSPAM-Confidence:」的所有行。在我提取它們之後,我想對它們調用sum()並計算平均值。謝謝,堆!在從文檔中提取的數字列表中調用sum()

 
for line in (fhand): 
    line = line.rstrip() 
    if not line.startswith("X-DSPAM-Confidence:"): 
     continue 
    else: 
     n = float(line[line.find(":") + 1:]) 
     a = sum(n) 
     count = count + 1 
    print (n) 
    print (a) 

print (total/count) 

回答

0

我不知道我的理解這個正確的,但就我所看到的,你只需要值的總和存儲在一個變量,像這樣:

total = 0.0 
count = 0 
for line in (fhand): 
    line = line.rstrip() 
    if not line.startswith("X-DSPAM-Confidence:"): 
     continue 
    else: 
     n = float(line[line.find(":") + 1:]) 
     total += n 
     count = count + 1 

print (total/count) 
+0

燁, 這樣可行!謝謝! –

相關問題