2015-11-04 57 views
1

大家好, 我想加載我有一個文件中的數據,它看起來像:閱讀數和規範

21.4,0.266667,0,0.966667,0.166667,0.966667,0.533333,0.1,............... 

現在,我想從文件加載這個並計算正常化。我做的:

f = open("Input.txt", "r") 
data = [line.strip() for line in f] 
print data 
norm = [float(i)/sum(data) for i in data] 
print norm 

但是,我得到的錯誤:

ValueError: invalid literal for float() 

雖然,我直接做加工成蟒蛇在linux像2.7控制檯,

a = [21.4,0.266667,0,0.966667,0.166667,0.966667,0.533333,0.1] 
norm = [float(i)/sum(a) for i in a] 
print norm 

這工作正常。我不知道我做錯了什麼。請幫助我,我是編程新手。提前致謝!

回答

2

您需要先將文件中的字符串轉換爲浮動。

data = [] 
with open('Input.txt') as f: 
    for line in f: 
     data.extend([float(x) for x in line.split(',')]) 

norm = [x/sum(data) for x in data] 
+1

是的,我正在努力,但你先到那裏:) – aychedee

+0

非常感謝輸入:) –