[英]Replace a section of 2D array with another 2D array just using python lists?
How can I slice a smaller array into an N x M array if I know the point of insertion? 如果知道插入点,如何将较小的阵列切成N x M的阵列?
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? 并仅使用列表推导?
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]]
Edit
I just realized now you have a using just list comprehensions
condition 我刚刚意识到您现在有了一个using just list comprehensions
条件
For that, you can use iter
and enumerate
为此,您可以使用iter
并enumerate
So given 因此给定
a1 = [[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],
[1,1,1,1,1,1,1,1,1,1]]
a2=[[1,2,3,4],
[5,6,7,8]]
x,y = (1,6)
You can do 你可以做
cols = len(a2[0])
ran = range(x,x+len(a2))
it = iter(a2)
final = [r if i not in ran else r[:y] + next(it) + r[(y+ncols):] for i,r in enumerate(a1)]
Use cases: 用例:
x,y = (2,6)
Output 产量
[[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, 2, 3, 4],
[1, 1, 1, 1, 1, 1, 5, 6, 7, 8]]
x,y = (1,4)
[[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, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
x,y = (0,0)
[[1, 2, 3, 4, 1, 1, 1, 1, 1, 1],
[5, 6, 7, 8, 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]]
Another solution is to use numpy
另一个解决方案是使用numpy
If you have 如果你有
import numpy as np
x = np.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]])
a = np.array([[1,2,3,4],
[5,6,7,8]])
You can use numpy indexing
您可以使用numpy indexing
x[1:,6:] = a
to get 要得到
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]])
If you are happy to use a 3rd party library, NumPy offers a generic solution for arbitrary coordinates: 如果您乐于使用第3方库,则NumPy可为任意坐标提供通用解决方案:
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]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.