pythonslice

Slicing a nested list based on other nested list


I am trying to slice sublists (arr) using elements from other sublists (slc). I am using Python. My code works just fine if there are no repeated values on the sublists to slice (arr). Otherwise, I cannot get the correct chunks.

arr[0] must be sliced with slc[0], arr[1] must be sliced with slc[1] and arr[2] must be sliced with slc[2].

Here is an example and the code I am using right now:

arr=[[5, 9, 8, 1, 0, 10, 11, 5], [13, 4, 13, 2, 5, 6, 13], [8, 25, 13, 9, 8, 7]]

slc=[[0, 5], [5, 13], [13, 7]]

rslt=[]

for i in range(len(arr)):
    rslt.append(arr[i][arr[i].index(slc[i][0]):arr[i].index(slc[i][1])+1])

current result:

rlst=[[], [], [13, 9, 8, 7]]

expected result:

rlst=[[0, 10, 11, 5], [5, 6, 13], [13, 9, 8, 7]] #expected results

My current code is not working for arr[0] and arr[1] because there are several elements from slc[0] and slc[1] on arr[0] and arr[1] respectively, so the slicing procedure is not working properly.


Solution

  • list.index() allows you to specify the starting index to start searching from. So use the index of the first item as this argument when looking for the end index.

    for a, (start, end) in zip(arr, slc):
        slice_start = a.index(start)
        slice_end = a.index(end, slice_start + 1)
        rslt.append(a[slice_start:slice_end + 1])