Python List accumulation

Sean picture Sean · Jun 18, 2014 · Viewed 21.2k times · Source

So the following code reads through two text files both containing 25 ints on 25 lines and puts them in two respective lists:

num_DIR = '/path/to/num.txt'
den_DIR = '/path/to/den.txt'

def makeList(DIR):
    list = []
    for line in open(DIR).readlines():
            list.append(line.strip())
    return list

num_list = makeList(num_DIR)
den_list = makeList(den_DIR)

Outputting:

num_list = ['76539', '100441', '108637', '108874', '103580', '91869', '78458', '61955', '46100', '32701', '21111', '13577', '7747', '4455', '2309', '1192', '554', '264', '134', '63', '28', '15', '12', '7', '5']

den_list = ['621266', '496647', '436229', '394595', '353249', '305882', '253983', '199455', '147380', '102872', '67255', '41934', '24506', '13778', '7179', '3646', '1778', '816', '436', '217', '114', '74', '49', '44', '26']

How would I go about making each value in both lists the added sum of all the value after it, as in an accumulation list?

Answer

Padraic Cunningham picture Padraic Cunningham · Jun 18, 2014

You seem to want the sum of all values to the end of the list after each element

summed=[]
den_list = map(int,den_list)
for i,j in enumerate(den_list[:-1]):
    summed += j,sum(den_list[i+1:])

If you don't want to keep the original values in the list

summed=[sum(num_list[i+1:])for i,j in enumerate(num_list[:-1])]