Sai nadupalli Sai nadupalli - 3 months ago 17
Python Question

Python list slicing

I'm not able understand what to do here. Can someone help.

I've a few lists:

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 = []


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


intermediate =intermediate + array[slice[i]:slice[i+1]+1]


here in my case:

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


intermediate = array[slice[0]:slice[0+1]+1] + array[slice[2]:slice[2+1]+1] + array[slice[4]:slice[4+1]+1]


which is

intermediate = array[2:(4+1)] + array[6:(8+1)] + array[10:(12+1)]


and when
slice[i] is interval[j]
output = output + intermediate
and the slicing is continued.

output = output + [intermediate]


which is

output = output + [array[2:(4+1)] + array[6:(8+1)] + array[10:(12+1)]]


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

The final output should be:

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]]


which is

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

Answer

A strait solution:

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]]

I have changed some variable names to avoid key words. On large data, you may convert intervals to a set.