Sums of entries, Python -



Sums of entries, Python -

possible duplicate: summing values of columns multiple files

i have little problem here, i'm trying sum entries multiple files (50), , each of them contain 3 columns. example, using first 3 files: file1.txt, file2.txt, file3.txt like:

file1.txt:

2 3 4 1 5 6 5 4 7

file2.txt:

1 2 1 2 3 2 4 3 1

file3.txt:

6 1 1 1 3 0 3 4 5

so question how sum entries column one, column 2 , column 3 50 files end file looks like:

output.txt:

9 6 6 4 11 8 12 11 13

i've read in 50 files , appended them i'm having problem summing entries 1 one.

so i've done this:

for p in range(50): locals()['first_col%d' % p] = [] locals()['second_col%d' % p] = [] locals()['third_col%d' % i] = [] in range(1,50): f = open("file"+str(i)+".txt","r") line in f: locals()['fist_col%d' % i].append(float(line.split()[0])) locals()['second_col%d' % i].append(float(line.split()[1])) locals()['third_col%d' % i].append(float(line.split()[2])) f.close()

i'm trying think of way set in loop read in first_cols (first_col1 ,first_col2, first_col3, etc), second_cols , third_cols , sum entries.

you utilize glob wildcard match filename pattern, bit of judicious utilize of zip , abuse literal_eval (might want consider generator convert int instead though) - nb - expects same number of columns , rows each file, otherwise truncation occur:

from glob import glob ast import literal_eval filenames = glob('/home/jon/file*.txt') files = [open(filename) filename in filenames] rows in zip(*files): nums = [literal_eval(row.replace(' ', ',')) row in rows] print map(sum, zip(*nums)) [9, 6, 6] [4, 11, 8] [12, 11, 13]

python

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -