how can i do math operation on list elements in python?

后端 未结 5 1822
北恋
北恋 2021-01-28 03:36

Suppose i have list of numbers [3, 51, 34]. I want to add to each element the sum of the previous elements and return a new list with these new values. So here the

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-28 04:08

    A list comprehension approach, because that's always fun:

    >>> data = [3, 51, 34]
    >>> result = [n + sum(data[:i]) for i, n in enumerate(data)]
    >>> result
    [3, 54, 88]
    

提交回复
热议问题