user3412058
user3412058

Reputation: 325

Adding certain elements of list

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?

Upvotes: 0

Views: 123

Answers (4)

Iron Fist
Iron Fist

Reputation: 10951

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]

Upvotes: 1

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

In [25]: map(sum, zip(*[iter(a)]*10))
Out[25]: [187, 237, 300, 197, 174, 282]

Upvotes: 3

Moses Koledoye
Moses Koledoye

Reputation: 78536

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

Upvotes: 2

Aran-Fey
Aran-Fey

Reputation: 43126

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]

Upvotes: 1

Related Questions