如何用列表中元素的总和替换列表中的每个元素,直到元素的位置(包括元素)



我有一个列表,其中包含每个月的天数:

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

我想转换上面的列表。新列表中的每个元素都等于特定位置中所有元素的总和。例如,第一个元素应该是相同的(31(,第二个=28+31,第三个=31+28+31,依此类推。期望输出:

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

怎么做?我尝试了for循环和append方法的变体,但没有成功。

虽然这没有标记为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]

最新更新