python - Difference of consecutive float numbers in a column -


i have list of floating point numbers in file in column this:

123.456

234.567

345.678

how can generate output file generated subtracting value in line value above it. input file above,the output generated should be:

123.456-123.456

234.567-123.456

345.678-234.567

the first value should return zero, other values should subtracted value above it. not homework question. small requirement of bigger problem , stuck @ point. appreciated. !!

this work:

diffs = [0] + [j - data[i] i,j in enumerate(data[1:])] 

so, assuming data.txt contains:

123.456 234.567 345.678 

then

with open('data.txt') f:     data = f.readlines()     diffs = [0] + [float(j) - float(data[i]) i,j in enumerate(data[1:])]  print diffs 

will yield

[0, 111.111, 111.11099999999999] 

this answer assumes want keep computed values further processing.

if @ point want write these out file, line line:

with open('result.txt', 'w') outf:     in diffs:         outf.write('{0:12.5f}\n'.format(i)) 

and adjust field widths suit needs (right 12 spaces reserved, 5 after decimal point), written out file result.txt.

update: given (from comments below) there possibly data hold in memory, solution should work. python 2.6 doesn't allow opening both files in same with, hence separate statements.

with open('result2.txt', 'w') outf:     outf.write('{0:12.5f}\n'.format(0.0))     prev_item = 0;     open('data.txt') inf:         i, item in enumerate(inf):             item = float(item.strip())             val = item - prev_item             if > 0:                 outf.write('{0:12.5f}\n'.format(val))             prev_item = item 

has bit of feel of hack. doesn't create huge list in memory though.


Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -