create sub lists by grouping with conditional check on two consecutive zeros
<p>I have a list:</p>

<pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10]
</code></pre>

<p>I want to create group of sublists with conditional break when a value is followed by two consecutive zeros.</p>

<p>so my intermediate list would like </p>

<pre><code>newlst = [-7,-8,-4,[-6,-4,-29,-10,-16],[2,3,18,-1,-2],[21,10,-10,-12,3,-5,-10]]
</code></pre>

<p>whereas the final output will be sum of sublists:</p>

<pre><code>[-7,-8,-4,-65,18,-3]
</code></pre>

<p>I tried using the index number in a for loop with enumerate but i'm not getting my desired output.</p>

<p>I group pairs of adjacent numbers by whether they hold any truth. Then take the truthy groups and sum them. Might be a bit too complicated, but I like using the <code>any</code> key.</p>

<pre><code>&gt;&gt;&gt; from itertools import groupby
&gt;&gt;&gt; [sum(a for a, _ in g) for k, g in groupby(zip(lst, lst[1:] + [0]), any) if k]
[-7, -8, -4, -65, 20, -3]
</code></pre>

<p>(Thanks to blhsing and ShadowRanger for improvements.)</p>

<p>Bit shorter way to turn the pairs back into singles (first is Python 2, second is Python 3):</p>

<pre><code>&gt;&gt;&gt; [sum(zip(*g)[0]) for k, g in groupby(zip(lst, lst[1:] + [0]), any) if k]
&gt;&gt;&gt; [sum(next(zip(*g))) for k, g in groupby(zip(lst, lst[1:] + [0]), any) if k]
</code></pre>

python python-2.7