Search code examples
pythonlistindexinglist-comprehensioncumulative-sum

Code Review Cumulative Totals of List Taking Snapshots at Index Python


another question about cumulative totals. Consider the following code:

json_message = {'result':[[12,  234],  [53,  45],  [3,  425],  [74,  12],  [3,  678],  [2,  42],  [12,  234],  [1,  66],  [6,  85],  [5,  73],  [12,  84],  [6,  24],  [98,  23],  [34,  4],  [82,  253]]}
total = 0
totals = [{'length': 1, 'total': 0},  {'length': 4, 'total': 0}, {'length': 7, 'total': 0}, {'length': 10, 'total': 0}, {'length': 15, 'total': 0}]

for index,  item in enumerate(json_message['result'][::-1]):
    total += round(float(item[1]),  2)
    if index == totals[0]['length']-1:
        totals[0]['total'] = total
    elif index == totals[1]['length']-1:
        totals[1]['total'] = total
    elif index == totals[2]['length']-1:
        totals[2]['total'] = total
    elif index == totals[3]['length']-1:
        totals[3]['total'] = total
    elif index == totals[4]['length']-1:
        totals[4]['total'] = total

print(totals)

I have a list of lists within json_message['result'], I'd like to get the sum of the 2nd int in each list getting a cumulative total at every nth index (indicated by length), in reverse. The code works, just looking for a more elegant solution.

I've also tried

json_message = {'result':[[12,  234],  [53,  45],  [3,  425],  [74,  12],  [3,  678],  [2,  42],  [12,  234],  [1,  66],  [6,  85],  [5,  73],  [12,  84],  [6,  24],  [98,  23],  [34,  4],  [82,  253]]}
total = 0
totals = [{'length': 1, 'total': 0},  {'length': 4, 'total': 0}, {'length': 7, 'total': 0}, {'length': 10, 'total': 0}, {'length': 15, 'total': 0}]

ind = (1, 4, 7, 10)

for index,  item in enumerate([[x[1] for x in json_message['result'][::-1]][start:stop] for start,stop in zip((0,)+ind, ind+(len(json_message['result']),))]):
for x in item:
    total += round(float(x),  2)
totals[index]['total'] = total

print(totals)

This also works, definitely shorter, not as elegant as I'd like. It works by seperating the second int int the list and reversing them by list comprehension. Then slices them into 5 list and finds the cumulative sum of each list.

Suggestions from the experts would be appreciated. Thank you.


Solution

  • No need to import numpy for such a simple task, something like this should work just fine:

    cumulative = 0
    for index, itm in enumerate(json_message['result'][::-1]):
        cumulative += itm[1]
        if index+1 in ind:
            print(cumulative)
    print(cumulative)