Re: file I/O and arithmetic calculation

Discussion in 'Python' started by Oscar Benjamin, May 23, 2013.

  1. On 22 May 2013 22:05, Carlos Nepomuceno <> 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) if s1c==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
     
    Oscar Benjamin, May 23, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Keira Wilson

    file I/O and arithmetic calculation

    Keira Wilson, May 22, 2013, in forum: Python
    Replies:
    2
    Views:
    135
    Carlos Nepomuceno
    May 23, 2013
  2. Mark Lawrence

    Re: file I/O and arithmetic calculation

    Mark Lawrence, May 22, 2013, in forum: Python
    Replies:
    0
    Views:
    108
    Mark Lawrence
    May 22, 2013
  3. Carlos Nepomuceno

    RE: file I/O and arithmetic calculation

    Carlos Nepomuceno, May 22, 2013, in forum: Python
    Replies:
    0
    Views:
    121
    Carlos Nepomuceno
    May 22, 2013
  4. Carlos Nepomuceno

    RE: file I/O and arithmetic calculation

    Carlos Nepomuceno, May 23, 2013, in forum: Python
    Replies:
    0
    Views:
    131
    Carlos Nepomuceno
    May 23, 2013
  5. Carlos Nepomuceno

    RE: file I/O and arithmetic calculation

    Carlos Nepomuceno, May 23, 2013, in forum: Python
    Replies:
    0
    Views:
    102
    Carlos Nepomuceno
    May 23, 2013
Loading...

Share This Page