0

I have a list that contain days count in each month:

month = [31,28,31,30,31,30,31,31,30,31,30,31]

I want to transform list above. Each element of the new list is equal to the sum of all elements in a particular position. For example, first element should be the same (31), second = 28+31, third = 31+28+31 and so on. Desired output:

month = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]

How to do it? I tried variations with a for loop and append method, but I did not succeed.

Dmitriy Kisil
  • 2,858
  • 2
  • 16
  • 35

1 Answers1

2

Though this isn't tagged numpy, I think you would greatly benefit from np.cumsum (cumulative sum) rather than looping:

import numpy as np

np.cumsum(month)

array([ 31,  59,  90, 120, 151, 181, 212, 243, 273, 304, 334, 365])

Alternatively, you could use this list comprehension:

[sum(month[:i+1]) for i in range(len(month))]

[31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]

As pointed out by @PatrickHaugh, you could also use itertools.accumulate:

import itertools

# Cast it to list to see results (not necessary depending upon what you want to do with your results)
list(itertools.accumulate(month))

[31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
sacuL
  • 49,704
  • 8
  • 81
  • 106