Kent,
Wow! That is all worth knowing. I am fascinated by the single sum
over a double loop.
Thanks,
Robert Berman
Kent Johnson wrote:
On Wed, Jan 21, 2009 at 2:02 PM, Robert Berman <[email protected]> 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 - [email protected]
http://mail.python.org/mailman/listinfo/tutor