0

I saw a lot of articles and answers to other questions about slicing 3D lists in python, but I can't apply those methods to my case.

I have a 3D list:

list = [
    [[0, 56, 78], [4, 86, 90], [7, 87, 34]],
    [[1, 49, 76], [0, 76, 78], [8, 60, 7]], 
    [[9, 6, 58], [6, 57, 78], [10, 46, 2]]
    ]

The the last 2 values of the 3rd dimension stay constant but change every time I rerun the code. What the code needs to do is find 2 specific pairs of those last 2 values and slice from one pair to the other. So for example:

pair1 = 86, 90
pair2 = 76, 78

The output should be:

[4, 86, 90], [7, 87, 34], [1, 49, 76], [0, 76, 78]

I know how to find the 2 pairs, I'm just not sure how to slice the list. Thanks in advance for your help and leave a comment if something is unclear.

2
  • Are you getting it to work? I mentioned in my answer. Build an array from the list: Check the updated answer Commented Apr 18, 2020 at 17:33
  • @yatu thanks that solution worked Commented Apr 18, 2020 at 17:35

1 Answer 1

2

Using numpy, you can slice the array to keep the last two elements on the last axis, find the indices where each pair takes place, flatten the result and use it to slice the array:

a = np.array(my_list) # don't call your list "list"

a_sliced = a[...,1:]

ix1 = np.flatnonzero((a_sliced  == pair1).all(-1).ravel()).item()

ix2 = np.flatnonzero((a_sliced  == pair2).all(-1).ravel()).item()

np.concatenate(a)[ix1:ix2+1]

array([[ 4, 86, 90],
       [ 7, 87, 34],
       [ 1, 49, 76],
       [ 0, 76, 78]])

a being defined as a numpy array, and both pairs defined as tuples:

pair1 = 86, 90
pair2 = 76, 78
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.