Python calculates the current sum of values ​​in one line

I am trying 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'}, ] 

Thus, it creates a list with values ​​updated as the current amount. Now I do this with a multi-line 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 a single line loop so that I get:

 return [{'value': somehow_incremented, 'date': element['date']} for element in some_data] 
+6
source share
3 answers

I would not recommend doing anything, your code is fine. Keep it readable.

In this case, the approach is:

 def values_incremented(some_data): return [{'value': current_sum, 'date': element['date']} for element, current_sum in zip(some_data, reduce(lambda x, y: [y['value']] if not x else x + [x[-1] + y['value']], some_data, []))] 
+3
source

You can write yourself the function of a storage generator. Use send to send values ​​to the generator and get a 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'}] 
+6
source

Here is one liner that works in linear time:

 reduce(lambda (c,s), a: (c + [{'value':s+a['value'], 'date':a['date']}], s+a['value']), some_data,([],0))[0] >>> [{'date': '2016-02-06', 'value': 2}, {'date': '2016-02-07', 'value': 3}, {'date': '2016-02-08', 'value': 8}, {'date': '2016-02-09', 'value': 11}, {'date': '2016-02-10', 'value': 12}] 

You should look at another current general question for a simpler version of the same problem.

+1
source

All Articles