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]
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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With