python - convert string to float in a loop -
i don't understand why not work. can me?
i have text file in data listed this.
04/05/2015 15:30 58.6
04/05/2015 16:00 56.3
...
each line has 3 space separated data.
i read
with open('./data') fi: data = [[t t in line.split() ]for line in fi] then variable has data
[['04/05/2015', '15:30', '58.6'], ['04/05/2015', '16:00', '56.3'], ... ] i'd take out data in 3rd column, made loop.
for t in data: a=float(t[2]) but got error
valueerror traceback (most recent call last) <ipython-input-76-83c96b309de0> in <module>() 2 i=0 3 t in data: ----> 4 a=float(t[2]) 5 valueerror: not convert string float: what don't understand if replace 'a=' 'print ', printed values.
for t in data: print float(t[2]) why not work substitution printing values?
it seems have unicode characters in input file. can specify encoding open file codecs.open:
import codecs codecs.open("input.txt", encoding="utf-8") f: data = [line.split() line in f] = [] row in data: print [col col in row] t in data: try: a.append(float(t[2])) except valueerror: break print(a) the above prints [58.6, 56.3] with
04/05/2015 15:30 58.6 04/05/2015 16:00 56.3 04/05/2015 16:00 \xc2\xa0 in input.txt.
Comments
Post a Comment