0

I want to add elements in a list every ten elements. For example:

a = [5, 31, 16, 31, 19, 5, 25, 34, 8, 13, 17, 17, 43, 9, 29, 41, 8, 24,
48, 1, 28, 20, 37, 40, 32, 35, 9, 36, 17, 46, 10, 30, 49, 28, 2, 3, 8,
11, 36, 20, 7, 24, 29, 15, 0, 4, 35, 11, 42, 7, 28, 40, 31, 45, 6, 45,
15, 27, 39,  6]

So I want to create a new list with the sum of every 10 elements, such as:

new = [187, 237, 300, 197, 174, 282]

Where the first entry corresponds to the add up of the first 10 numbers:

x = sum(5, 31, 16, 31, 19, 5, 25, 34, 8, 13)
x = 187

The second one to the 10 numbers in the range 10-19:

y = sum(17, 17, 43, 9, 29, 41, 8, 24, 48, 1)
y = 237

And so on; is there an efficient way to do this?

Iron Fist
  • 10,739
  • 2
  • 18
  • 34
user3412058
  • 315
  • 1
  • 4
  • 13
  • Possible duplicate of [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – Mureinik Jul 24 '16 at 16:06

4 Answers4

3
In [25]: map(sum, zip(*[iter(a)]*10))
Out[25]: [187, 237, 300, 197, 174, 282]
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
2

Use map on an iterator of the list:

>>> it = iter(a)
>>> map(lambda *x: sum(x), *(it,)*10)
[187, 237, 300, 197, 174, 282]

Create an iterator for your list. Pass the items to map in 10s using the iterator and use map to return the sum of the passed parameters.

Python 3.x will require an explicit list call on map

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

You can use nested comprehensions with a list iterator:

i= iter(a)
s= [sum(next(i) for _ in range(10)) for _ in range(len(a)//10)]
print s

Note that this will silently ignore any leftover values:

a= [1]*11 #<- list has 11 elements
i= iter(a)
s= [sum(next(i) for _ in range(10)) for _ in range(len(a)//10)]
print s
# output: [10]
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
1

How about list comprehension, like this one:

>>> step = 10
>>> 
>>> [sum(a[x:x+step]) for x in range(0, len(a), step)]
[187, 237, 300, 197, 174, 282]
Iron Fist
  • 10,739
  • 2
  • 18
  • 34