Python list slicing
<p>I'm not able understand what to do here. Can someone help.</p>

<p>I've a few lists:</p>

<pre><code>array = [7,8,2,3,4,10,5,6,7,10,8,9,10,4,5,12,13,14,1,2,15,16,17]
slice = [2, 4, 6, 8, 10, 12, 15, 17, 20, 22]
intervals = [12, 17, 22]
output = []
intermediate = []
</code></pre>

<p><code>slice</code> is a list of indices I need to get from slicing <code>array</code>. <code>interval</code> is a list of indices used to stop the slicing when <code>slice[i] is interval[j]</code> where i and j are looping variables.
I need to form a list of lists from <code>array</code> based on <code>slice</code> and <code>intervals</code> based on the condition that when <code>slice[i] is not interval[j]</code> </p>

<pre><code>intermediate =intermediate + array[slice[i]:slice[i+1]+1]
</code></pre>

<p>here in my case:</p>

<p>when <code>slice[i]</code> and <code>interval[j]</code> are equal for value 12. So I need to form a list of lists from <code>array</code> </p>

<pre><code>intermediate = array[slice[0]:slice[0+1]+1] + array[slice[2]:slice[2+1]+1] + array[slice[4]:slice[4+1]+1]
</code></pre>

<p>which is</p>

<pre><code>intermediate  = array[2:(4+1)] + array[6:(8+1)] + array[10:(12+1)]  
</code></pre>

<p>and when <code>slice[i] is interval[j]</code> <code>output = output + intermediate</code> and the slicing is continued.</p>

<pre><code>output = output + [intermediate]
</code></pre>

<p>which is</p>

<pre><code>output = output + [array[2:(4+1)] + array[6:(8+1)] + array[10:(12+1)]]
</code></pre>

<p>now the next value in interval is 17 so till we have 17 in <code>slice</code> we form another list from <code>array[slice[6]:slice[6+1]+1]</code> and add this to the output. This continues.</p>

<p>The final output should be:</p>

<pre><code>output = [array[slice[0]:slice[0+1]+1] + array[slice[2]:slice[2+1]+1] + array[slice[4]:slice[4+1]+1] , array[slice[6]:slice[6+1]+1], array[slice[8]:slice[8+1]+1]]
</code></pre>

<p>which is</p>

<pre><code>output = [[2, 3, 4, 5, 6, 7, 8, 9, 10], [12, 13, 14], [15, 16, 17]]
</code></pre>

<p>A straightforward solution:</p>

<pre><code>array_ = [7,8,2,3,4,10,5,6,7,10,8,9,10,4,5,12,13,14,1,2,15,16,17]
slice_ = [2, 4, 6, 8, 10, 12, 15, 17, 20, 22]
intervals = [12, 17, 22]
output = []
intermediate = []

for i in range(0, len(slice_), 2):
    intermediate.extend(array_[slice_[i]:slice_[i+1]+1])
    if slice_[i+1] in intervals:
        output.append(intermediate)
        intermediate = []

print output
# [[2, 3, 4, 5, 6, 7, 8, 9, 10], [12, 13, 14], [15, 16, 17]]
</code></pre>

<p>I have changed some variable names to avoid conflicts.
On large data, you may convert <code>intervals</code> to a set.</p>

python list