2016-06-13 48 views
0

所以我想做一個列表,其中包含數字列表的運行總數,但我仍然希望顯示第一個數字而不添加任何內容,例如:數字不正確添加

輸入
0.1
0.3
0.2
0.4
0.2

所需的輸出
0.1
0.4
0.6
1.0
1.2

輸出我得到
0.4
0.6
1.0
1.2

這裏是我一起工作的代碼:

open('widthdepth1.txt','w').writelines([ line for line in open("Test1.txt") if "WIDTH" in line or "DEPTH" in line]) 

for line in open("widthdepth1.txt"): 
line = line.strip("") 
parts = line.split(":") 
category = parts[0] 
value = parts[1] 

with open("widthdepth1.txt") as f: 
width = [line.split(":")[1] for line in f if "WIDTH" in line] 
widthtotal = float(width[0]) 
h = open("WidthValue1.txt", "w") 
for line in width[1:19]: 
widthtotal += float(line) 
h.write(str("%0.4f" %widthtotal)+"\n") 
print ("%0.4f" %widthtotal) 

我是新來的python,所以任何幫助將不勝感激。

+1

請修復您的縮進。 – zondo

回答

1
widthtotal = float(width[0]) 
h = open("WidthValue1.txt", "w") 
for line in width[1:19]: 
    widthtotal += float(line) 

widthtotal已經包含0.1循環開始前,你打印任何東西之前0.3被添加到它。所以0.1未被打印並不令人驚訝。嘗試將widthtotal初始化爲零,然後迭代完整的width集合。

widthtotal = 0 
h = open("WidthValue1.txt", "w") 
for line in width: 
    widthtotal += float(line) 
+0

非常感謝這個工作!非常感激。 –