Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python compute running sum of values in one-line

I try to process such data:

some_data = [
                {'value': 2, 'date':'2016-02-06'},
                {'value': 1, 'date':'2016-02-07'},
                {'value': 5, 'date':'2016-02-08'},
                {'value': 3, 'date':'2016-02-09'},
                {'value': 1, 'date':'2016-02-10'},
            ]

So that it produces a list with values updated to be a running sum. Now I do it with a multiline loop:

def values_incremented(some_data):
    temp_sum = 0
    result = []
    for element in some_data:
        temp_sum += element['value']
        result.append({'value': temp_sum, 'date': element['date']})
    return result

How to make the loop one-liner, so that I got:

return [{'value': somehow_incremented, 'date': element['date']} for element in some_data]
like image 276
alekwisnia Avatar asked Feb 24 '16 14:02

alekwisnia


1 Answers

You could write yourself an accumulating generator function. Use send to send values into the generator and get the new sum.

def accumulator(n=0):
    while True:
        n += yield n

acc = accumulator(0)
acc.send(None)

res = [{'value': acc.send(element['value']), 'date': element['date']} for element in some_data]

As a result, res is

[{'value': 2, 'date': '2016-02-06'}, 
 {'value': 3, 'date': '2016-02-07'}, 
 {'value': 8, 'date': '2016-02-08'}, 
 {'value': 11, 'date': '2016-02-09'}, 
 {'value': 12, 'date': '2016-02-10'}]
like image 186
tobias_k Avatar answered Oct 10 '22 12:10

tobias_k