1

The situation is the following:

Lets say I have two arrays, x and y: Input:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
y = [2,6,9,13]

Expected output:

arr1 = [2,3,4,5]
arr2 = [6,7,8]
arr3 = [9,10,11,12]

I would like to create a python script that can let me split up array x into multiple arrays based on the values of array y as the end points.

So x will split up between 2 and 6, then between 6 and 9, then between 9 and 13 in this example.

I am not sure how to get started on this, I am a beginner. I would appreciate the help and I would love to know how you broke down the problem to solve it? Thank you!

4
  • 2
    Could you define the rules for us as it's not obvious? Commented May 27, 2020 at 20:42
  • 1
    In arr1, 2 is the starting point whereas in arr2 and arr3, 9 and 13 are ending points of y Commented May 27, 2020 at 20:46
  • shouldn't arr1 be equal to [2,3,4,5,6] then, as I understand your values in y should determine end/start values of the output lists Commented May 27, 2020 at 20:46
  • sorry! just fixed what I wanted Commented May 27, 2020 at 20:50

3 Answers 3

1

Find the index of x based on value in y and then use indexing

arr = []
for i in range(len(y)-1):
    arr.append(x[x.index(y[i]):x.index(y[i+1])])

arr

[[2, 3, 4, 5], [6, 7, 8], [9, 10, 11, 12]]

This works if there are duplicates in the array,

x = [2,3,4,5,6,7,7,8,9,9,10,11,11,12,13,14,15]
y = [2,6,9,13]

arr = []
for i in range(len(y)-1):
    arr.append(x[x.index(y[i]):x.index(y[i+1])])

[[2, 3, 4, 5], [6, 7, 7, 8], [9, 9, 10, 11, 11, 12]]
Sign up to request clarification or add additional context in comments.

Comments

1

For x sorted, we can use np.searchsorted with np.split to split x using the indices where y is contained in x:

import numpy as np

i = np.searchsorted(x, y)
np.split(x,i+1)[1:-1]
# [array([3, 4, 5, 6]), array([7, 8, 9]), array([10, 11, 12, 13])]

3 Comments

My bad! Yeah I fixed the response
This code doesn't look at values in y at all, try the same code for x = [2,3,4,5,6,7,8,9,10,11,12,13,14,15]
Updated. Same idea but finding the indices through searchsorted @vaishal
0

You are somewhat inconsistent in your expected output, or I don`t get the pattern behind it, but this should get you close to what you want

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
y = [2,6,9,13]

m = []

for i in range(len(y) - 1):
    m += [x[y[i] - 1:y[i+1] - 1]]

print(m)

Output

[[2, 3, 4, 5], [6, 7, 8], [9, 10, 11, 12]]

2 Comments

This code doesn't look at values in y at all, try the same code for x = [2,3,4,5,6,7,8,9,10,11,12,13,14,15]
It does but interprets them as indices, the example was kind of vague on what was expected.

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.