user5124826
user5124826

Reputation:

For Loop adding 5 numbers at a time

I have a file that contains a list of numbers ex:

1
2
3
4
5
6
7
8
9
10

How would I be able to read the first five numbers, compute the sum, and then read in the next five numbers? Could I use a for loop? I want my answer to look like this:

var1 = 15
var2 = 40

Is there an easier way than using a for loop?

Upvotes: 1

Views: 866

Answers (3)

Ashutosh Chapagain
Ashutosh Chapagain

Reputation: 926

Keep in mind for loop in python is equivalent to for each conceptually. It would be better to use a while statement with a condition to stop reading after you have gotten the inputs you want.

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54183

You can use the itertools grouper recipe, which is useful in lots of applications!

import itertools

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.zip_longest(*args, fillvalue=fillvalue)

sums = []

with open(filename) as f:
    groups = grouper(f)
    for group in groups:
        sum_ = sum(int(line) for line in group)
        sums.append(sum_)

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

you can use next on the file handle and convert to integer, pass to sum in a generator comprehension, then unpack to 2 variables, with a default 0 value just in case the file ends before 10 values (next(f,0) does that)

with open("input.txt") as f:
   var1,var2 = (sum(int(next(f,0)) for _ in range(5)) for _ in range(2))

Upvotes: 3

Related Questions