On Wed, Jan 21, 2009 at 2:02 PM, Robert Berman <berma...@cfl.rr.com> wrote:

>   myfile = openinput()
>   for line in myfile:
>       jlist = line.split()
>       for x in jlist:
>           bigtotal += int(x)

Python has a sum() function that sums the elements of a numeric
sequence, so the inner loop can be written as
  bigtotal += sum(int(x) for x in line.split())

But this is just summing another sequence - the line sums - so the
whole thing can be written as
  bigtotal = sum(sum(int(x) for x in line.split()) for line in myfile)

or more simply as a single sum over a double loop:
  bigtotal = sum(int(x) for line in myfile for x in line.split())

which you may or may not see as an improvement...

Kent
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to