虽然这个没有标签
numpy
我想你会从中受益匪浅
np.cumsum
(累积和)而不是循环:
import numpy as np
np.cumsum(month)
array([ 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365])
或者,您可以使用此列表理解:
[sum(month[:i+1]) for i in range(len(month))]
[31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
正如@patrickhaugh指出的,您也可以使用
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]