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>Best I could find is a two line solution:</p>

<pre><code>breaks=[0]+[sum(v[:i+1]) for i in range(len(v))]  #build a list of section indices
result=[l[breaks[i]:breaks[i+1]] for i in range(len(breaks)-1)]  #split array according to indices
print result
</code></pre>

python python-2.7