【问题标题】:How to replace each element of the list with the sum of the elements of the list up to the position of the element inclusive [duplicate]如何用列表中元素的总和替换列表中的每个元素,直到包含元素的位置[重复]
【发布时间】:2018-07-15 16:22:53
【问题描述】:

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

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 方法的变体,但没有成功。

【问题讨论】:

    标签: python python-3.x for-loop sum


    【解决方案1】:

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

    【讨论】:

    • 谢谢,这正是我所需要的(列表理解)
    • 很高兴能帮上忙!
    • 我会使用 itertools.accumulate 而不是导入 numpy(假设您使用的是 Python >= 3.2)
    • 谢谢@PatrickHaugh,我将它包含在我编辑的答案中(感谢:))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 2018-04-15
    • 1970-01-01
    • 2021-11-26
    • 2021-04-17
    • 2020-03-27
    • 2017-07-05
    相关资源
    最近更新 更多