List comprehension: Creating new list by adding multiple values in single list

1169 views python
9

Given a list containing monthly numerical data, how can I easily convert this into quarterly data?

x= [5,8,3,4,5,6,1,2,5,3,11,8] #monthly data for Jan-Dec

Desired output:

[5+8+3, 4+5+6, 1+2+5, 3+11+8] #converted to quarterly data

I wanted to do something like [a+b+c for a,b,c in x] but x it says x is not iterable.

answered question

Cutting the list into parts is typically known as "partitioning". You might be able to find something if you search that. Then once you have it partitioned, you just need to sum each partition.

1 Answer

13

A list comprehension way:

[sum([x[i],x[i+1],x[i+2]]) for i in range(0,len(x),3)]
#[16, 15, 8, 22]

And a numpy way:

import numpy as np

np.sum(np.array(x).reshape(-1,3),axis=1)
#array([16, 15,  8, 22])

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories