ivanhoifung
ivanhoifung

Reputation: 349

Adding up number in a list with every 3 number

I have a list of numbers go in one row like this:

0
1
0
2
0
4

and it has about thousands of rows

I want to add them up every 3 rows so the results will be like this:

1
6

I have already made the list into individual integer with this line:

k = map(lambda s: s.strip(), k)
integer = map(int, k)

How would I able to do the adding up?

Upvotes: 3

Views: 1320

Answers (6)

Rusty Rob
Rusty Rob

Reputation: 17173

This is probably the most pythonic:

>>> my_list = iter(my_list)
>>> map(sum, zip(my_list, my_list, my_list))
[1, 6]

Upvotes: 1

Rusty Rob
Rusty Rob

Reputation: 17173

This will skip the remaining numbers that can't fit into a group of three:

>>> def sum_three(iterable_):
...     iterable_ = iter(iterable_)
...     while True:
...         yield next(iterable_) + next(iterable_) + next(iterable_)
...
>>> my_list = [0, 1, 0, 2, 0, 4, 99, 1]
>>> list(sum_three(my_list))
>>> [1, 6]

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121306

Use a grouper, like from Alternative way to split a list into groups of n:

import itertools

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(*args, fillvalue=fillvalue)

map(sum, grouper(3, interger, 0))

Note that the above code assumes python 2.x; for 3.x you'll need to use itertools.zip_longest instead.

Demo:

>>> example = [0, 1, 0, 2, 0, 4]
>>> map(sum, grouper(3, example, 0))
[1, 6]

Upvotes: 4

Levon
Levon

Reputation: 143027

Since you say you already have a list of numbers, then

result = [sum(data[i:i+3])for i in range(0, len(data),3)]

e.g.,

 data = range(1, 16) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

yields

 [6, 15, 24, 33, 42]

Upvotes: 1

Maria Zverina
Maria Zverina

Reputation: 11163

Grouper and all the fancy stuff will work ... but simple list comprehension will do in this case. And it should be nice and fast! :)

>>> q = range(9)
>>> q
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> [sum(q[3*n:3*n+3]) for n in range(len(q)/3)]
[3, 12, 21]

Upvotes: 0

jamylak
jamylak

Reputation: 133504

Using itertools grouper recipe

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

>>> with open('data.txt') as fin:
        for g in grouper(3, fin):
            print sum(map(int, g))


1
6

Upvotes: 0

Related Questions