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>

<pre><code>reduce(
        lambda lst,item: (((item[0] != '') and lst) or lst[:-1]) + [lst[-1] + item[1]],
        colLabelGrouped[1:],
        [colLabelGrouped[0][1]] )
</code></pre>

<p>This reduction...</p>

<ul>
<li>starts with an initial list consisting of the value of the first item in <code>colLabelGrouped</code>, then</li>
<li>reduces the remaining items in <code>colLabelGrouped</code> by...

<ul>
<li>appending the value of each item in turn added to the last element of the list being produced to <em>either</em>...

<ul>
<li>the complete list (if the item's key is not empty) or</li>
<li>the list minus the last element (if the item's key is empty).</li>
</ul></li>
</ul></li>
</ul>

python list tuples