file I/O and arithmetic calculation
Carlos Nepomuceno
carlosnepomuceno at outlook.com
Wed May 22 23:15:58 EDT 2013
The last line of my noob piece can be improved. So this is it:
### 1strow_average.py ###
#Assuming you have CSV (comma separated values) files such as:
#1.txt = '0,1,2,3,4,5,6,7,8,9\n' \
# '10,11,12,13,14,15,16,17,18,19\n' \
# '20,21,22,23,24,25,26,27,28,29\n' ...
#
# Usage: contents[file][row][column]
# contents[0] : file '1.txt'
# contents[1][2] : 3rd row of file '2.txt'
# contents[3][4][5] : value on the 6th column of 5th row of file '4.txt'
# len(contents) : quantity of files
# len(contents[4]) : quantity of lines in file '5.txt'
# len(contents[4][0]: quantity of values in the 1st line of file '5.txt'
filenames = ['1.txt', '2.txt', '3.txt', '4.txt', '5.txt']
contents = [[[int(z) for z in y.split(',')] for y in open(x).read().split()] for x in filenames]
s1c = [sum([r[0] for r in f]) for f in contents]
a1r = [sum(f[0])/float(len(f[0])) for f in contents]
print '\n'.join(['File "{}" has 1st row average = {:.2f}'.format(n,a1r[i]) for i,n in enumerate(filenames) if s1c[i]==50])
More information about the Python-list
mailing list