slice a list based on some values
<p>Hi I'm looking for a way to split a list based on some values, and assuming the list's length equals to sum of some values, e.g.:</p>

<p>list: <code>l = ['a','b','c','d','e','f']</code>
values: <code>v = (1,1,2,2)</code>
so <code>len(l) = sum(v)</code></p>

<p>and I'd like to have a  function to return a tuple or a list, like: <code>(['a'], ['b'], ['c','d'], ['d','e'])</code></p>

<p>currently my code is like:</p>

<pre><code>(list1,list2,list3,list4) = (
    l[0:v[0]], 
    l[v[0]:v[0]+v[1]], 
    l[v[0]+v[1]:v[0]+v[1]+v[2]], 
    l[v[0]+v[1]+v[2]:v[0]+v[1]+v[2]+v[3]])`
</code></pre>

<p>I'm thinking about make this clearer, but closest one I have so far is (note the results are incorrect, not what I wanted)</p>

<pre><code>s=0
[list1,list2,list3,list4] = [l[s:s+i] for i in v]
</code></pre>

<p>the problem is I couldn't increase <code>s</code> at the same time while iterating values in <code>v</code>, I'm hoping to get a better code to do so, any suggestion is appreciated, thanks!</p>

<p>If you weren't stuck on ancient Python, I'd point you to <a href="https://docs.python.org/3/library/itertools.html#itertools.accumulate" rel="nofollow"><code>itertools.accumulate</code></a>. Of course, even on ancient Python, you could use the (roughly) equivalent code provided in the docs I linked to do it. Using either the Py3 code or equivalent, you could do:</p>

<pre><code>from itertools import accumulate  # Or copy accumulate equivalent Python code
from itertools import chain

# Calls could be inlined in listcomp, but easier to read here
starts = accumulate(chain((0,), v))  # Extra value from starts ignored when ends exhausted
ends = accumulate(v)
list1,list2,list3,list4 = [l[s:e] for s, e in zip(starts, ends)]
</code></pre>

python python-2.7