T
T
Timebird2016-04-03 00:47:28
Python
Timebird, 2016-04-03 00:47:28

How to create a list with sums of elements of another list?

Hello! The question is the following.
There is a list_1, in which, let's say, 80 elements. You need to assign each of these elements a list with the sum up to the index of this element.
For example.
Assign the second element a list with the sum of the first and second elements of list_1.
Assign the third element a list with the sum of the first, second and third elements of list_1.
The fourth element is assigned a list with the sum of the first, second, third and fourth elements of list_1.
and so on until the 80th.
Here I am trying to do it, but without success:

sum = 0
for elem in range(int(list_1[1]), int(list_1[-1])):
    list_with_summs[elem] = [] #сначала на каждый из элементов создаю свой список
    sum += elem #потом считаю сумму до соответствующего элемента
    list_with_summs[elem].append(sum) #соответствующему списку присваиваю соответствующую сумму
print('List with sums: ', list_with_summs)

list_1is given to the entrance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Surin, 2016-04-03
@Timebird

To be honest, I didn’t quite understand what and what you wanted to get from, but I hope the code below will help you.

sum = [2, 3, 2, 5, 6]
res = []
for k,v in enumerate(sum):
    if (k>0):
        res.append(res[k-1] + sum[k])
    else:
        res.append(sum[k])
print(sum)
print(res)
# Вывод
[2, 3, 2, 5, 6]
[2, 5, 7, 12, 18]

M
Maxim Moseychuk, 2016-04-03
@fshp

import itertools
import operator

itertools.accumulate([1,2,3,4,5], operator.add)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question