Split tuple if key is empty and add correspondence value to its previous tuple value
<p>Here i have a list of tuples,whenever key is empty i want to add correspondence value to its previous tuple value.</p>

<p>I am able to achieve this in traditional way, but it looks ugly,
Is there any pythonic way to achieve the same ?</p>

<p>input : </p>

<pre><code>data= [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)]
</code></pre>

<p>expected output :</p>

<pre><code>[13, 26, 39, 52]
</code></pre>

<p>My CODE:</p>

<pre><code>data = [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)]
init = 0 ; splitdata = []
for i in data:
    init = init+i[1]
    if i[0] == '':
        splitdata.append(init)
splitdata.append(init)
print(splitdata)
[13, 26, 39, 52]
</code></pre>

<p>Here's a slightly shorter way of doing it using the accumulate function and list-comprehensions (it might be more readable too):</p>

<pre><code>colLabelGrouped = [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)]

from itertools import accumulate
cumsum = list(accumulate([x[1] for x in colLabelGrouped]))
result = [cumsum[i] for i,x  in enumerate(colLabelGrouped) if x[0] == ""] 

if colLabelGrouped[-1][0] != "":
    result.append(cumsum[-1])

print(result)
</code></pre>

python list tuples