Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #45757

Re: file I/O and arithmetic calculation

References <CAK9meDsND9501=2ydmCAFi4s6+fw+rTrDGJA2qpEyXKoae6Axw@mail.gmail.com> <BLU176-W17E5DA2B650B3CE80F79BFD7A90@phx.gbl>
From Oscar Benjamin <oscar.j.benjamin@gmail.com>
Date 2013-05-23 00:43 +0100
Subject Re: file I/O and arithmetic calculation
Newsgroups comp.lang.python
Message-ID <mailman.1979.1369266216.3114.python-list@python.org> (permalink)

Show all headers | View raw


On 22 May 2013 22:05, Carlos Nepomuceno <carlosnepomuceno@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: file I/O and arithmetic calculation Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2013-05-23 00:43 +0100

csiph-web