Python - merge sub lists that match certain pattern in another list? : <p>Don't know how to name such pattern, but by examples I think it is easier to explain.</p>

<p>For example let say I have this list:</p>

<pre><code>lst = [1, 2, 3, 5, 6, 7, 8, 10, 11, 15]
</code></pre>

<p>So Now I need to merge part of list that goes by increment of one (meaning only first and last items ar kept), but if there only two items in such increment, there is nothing to merge, because they are both first and last items of such pattern.</p>

<p>So by running some method that handles this, it should separate it in this:</p>

<pre><code>merged = [(1, 3), (5, 8)]
original = [10, 11, 15]
</code></pre>

<p>Note on original list. It has those three items only, because <code>2</code>, <code>6</code> and <code>7</code> are merged (they match that pattern). <code>10</code> and <code>11</code> goes by one increment, but there are only two numbers, so there is nothing to merge. And <code>15</code> does not match any pattern at all.</p>

<p>I thought of using some comparison of first and second items on iteration, but algorithm got complicated and I was not able to properly merge/detach those items.</p>

<p>P.S.</p>

<p>And the reason for this is I have a module that generates excel reports. And it is possible to specify formulas how some rows need to be computed (on excel side).</p>

<p>Now current functionality returns specific (when separate part of sheet are used in one formula) rows numbers. So for example formula could end up something like: <code>"sum(A1, A2, A3, A5)"</code>. And if there lots of rows, actual expression could become very big. But if I could simplify it by having that same formula for exmaple <code>"sum(A1:A3, A5)"</code> it would not be so big.</p>
