Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #45757 > unrolled thread
| Started by | Oscar Benjamin <oscar.j.benjamin@gmail.com> |
|---|---|
| First post | 2013-05-23 00:43 +0100 |
| Last post | 2013-05-23 00:43 +0100 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: file I/O and arithmetic calculation Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2013-05-23 00:43 +0100
| From | Oscar Benjamin <oscar.j.benjamin@gmail.com> |
|---|---|
| Date | 2013-05-23 00:43 +0100 |
| Subject | Re: file I/O and arithmetic calculation |
| Message-ID | <mailman.1979.1369266216.3114.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web