1

Let's say I have a python list:

[4,5,25,60,19,2]

How can I add every nth entry to each other?

e.g. I split the list into 3 entries [ 4,5 / 25,60 / 19,2 ], then add these entries in order to get a new list:

[4+25+19, 5+60+2]

Which gives me the sum:

[48, 67]

For a more complex example, lets say I have 2000 entries in my list. I want to add every 100th entry to the one before so I get 100 entries in the new list. Each entry would now be the sum of every 100th entry.

cs95
  • 379,657
  • 97
  • 704
  • 746
pylab
  • 77
  • 1
  • 6

4 Answers4

4

Iteratively extract your slices and sum them up.

>>> [sum(l[i::2]) for i in range(len(l) // 3)]
[48, 67]

You may have to do a bit more to handle corner cases but this should be a good start for you.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • This would work, but I've edited my question to fit 2D lists instead. With 2D lists I wouldn't have to convert my list to a 1D list. Do you know if I could use this same method with 2D lists? – pylab Oct 21 '18 at 20:53
  • @pylab `list(map(sum, my_list))` – cs95 Oct 21 '18 at 21:00
1

The itertools documentation has a recipe function called grouper, you can import it from more_itertools (needs manual install) or copy paste it.

It works like this:

>>> from more_itertools import grouper
>>> l = [4,5,25,60,19,2]
>>> list(grouper(2, l)) # 2 = len(l)/3
>>> [(4, 5), (25, 60), (19, 2)]

You can transpose the output of grouper with zip and apply sum to each group.

>>> [sum(g) for g in zip(*grouper(2, l))]
>>> [48, 67]

I prefer this to manually fiddling with indices. In addition, it works with any iterable, not just lists. A generic iterable may not support indexing or slicing, but it will always be able to produce a stream of values.

timgeb
  • 76,762
  • 20
  • 123
  • 145
0

Using the chunks function taken from here, you could write the following:

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

l = [4,5,25,60,19,2]
print([sum(e) for e in list(chunks(l, 2))])
Felix
  • 1,837
  • 9
  • 26
0

There may be a smart sequence of list operations that you could use but I couldn't think of any. So instead I just did a parser that goes from 0 to n-1 and within the confines of the list adds the elements, going every n. So if n=3, you go 0, 3, 6, etc; then 1, 4, 7, etc. - and put it into the output list.

The code is attached below. Hope it helps.

list1 = [7, 6, -5.4, 6, -4, 55, -21, 45, 67, -9, -8, -7, 8, 9, 11, 110, -0.8, -9.8, 1.1]
n = 5

list2 = []
sum_elem = 0

for i in range(n):
    sum_elem = 0
    j = i

    while j < len( list1 ):
        sum_elem += list1[j]
        j += n

    list2.append(sum_elem)

print( list2 )