-1

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.

I don't think this is a duplicate. I am specifically looking for a list comprehension solution.

Sean Mahoney
  • 131
  • 7
  • 2
    Possible duplicate of [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – Mureinik Sep 15 '18 at 15:56

2 Answers2

1

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]

Or in a nicer way (thanks @JonClements):

[sum(x[i:i+3]) for i in range(0, len(x), 3)]

And a numpy way:

import numpy as np

np.sum(np.array(x).reshape(-1,3),axis=1)
#array([16, 15,  8, 22])
sacuL
  • 49,704
  • 8
  • 81
  • 106
0

Not getting to crazy you could just slice them up and then work with each group

x= [5,8,3,4,5,6,1,2,5,3,11,8]

a, b, c, d = x[:3], x[3:6], x[6:9], x[9:12]

print(a, b, c, d)
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 slice_q.py 
[5, 8, 3] [4, 5, 6] [1, 2, 5] [3, 11, 8]

From here if you want to sum each group you could do something like this

lista = [a, b, c, d,]

for i in lista:
    print(sum(i))
16
15
8
22
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20