file I/O and arithmetic calculation
Oscar Benjamin
oscar.j.benjamin at gmail.com
Wed May 22 19:43:08 EDT 2013
On 22 May 2013 22:05, Carlos Nepomuceno <carlosnepomuceno at outlook.com> wrote:
>
> 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([x for x in ['File "{}" has 1st row average = {:.2f}'.format(n,a1r[i]) if s1c[i]==50 else '' for i,n in enumerate(filenames)] if x])
Do you find this code easy to read? I wouldn't write something like
this and I certainly wouldn't use it when explaining something to a
beginner.
Rather than repeated list comprehensions you should consider using a
single loop e.g.:
for filename in filenames:
# process each file
This will make the code a lot simpler.
Oscar
More information about the Python-list
mailing list