0

How can I slice a smaller array into an N x M array if I know the point of insertion?

ie,

# Larger array
[1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1]

# Smaller array
[1,2,3,4]
[5,6,7,8]

# Insert at [1,6] gives:
[1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,2,3,4]
[1,1,1,1,1,1,5,6,7,8]

And using just list comprehensions?

2 Answers 2

1
l = [[1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1]]
s = [[1,2,3,4],
[5,6,7,8]]
def insert(large, small, row, col):
    for i, r in enumerate(small):
        large[row + i][col:col + len(r)] = r
insert(l, s, 1, 6)
print(l)

This outputs:

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

Comments

0

If you are happy to use a 3rd party library, NumPy offers a generic solution for arbitrary coordinates:

i, j = (1, 6)

x[i:i+a.shape[0], j:j+a.shape[1]] = a

print(x)

array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 2, 3, 4],
       [1, 1, 1, 1, 1, 1, 5, 6, 7, 8]])

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.