如何将一个数组复制到另一个数组

问题描述 投票:0回答:1

我正在尝试在8x8 2D数组中放入一个小的8x7 2D数组。

这是我正在使用的东西:

--> Array called 'a' with shape 8x7

a = [[ 16.,  11.,  10.,  16.,  24.,  40.,  51.],
     [ 12.,  12.,  14.,  19.,  26.,  58.,  60.],
     [ 14.,  13.,  16.,  24.,  40.,  57.,  69.],
     [ 14.,  17.,  22.,  29.,  51.,  87.,  80.],
     [ 18.,  22.,  37.,  56.,  68., 109., 103.],
     [ 24.,  35.,  55.,  64.,  81., 104., 113.],
     [ 49.,  64.,  78.,  87., 103., 121., 120.],
     [ 72.,  92.,  95.,  98., 112., 100., 103.]]


--> Array called 'b' with shape 8x8

b = [[0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0., 0.]]

基本上,我想要的是:

--> Array called 'c' with shape 8x8

c = [[ 16.,  11.,  10.,  16.,  24.,  40.,  51., 0],
     [ 12.,  12.,  14.,  19.,  26.,  58.,  60., 0],
     [ 14.,  13.,  16.,  24.,  40.,  57.,  69., 0],
     [ 14.,  17.,  22.,  29.,  51.,  87.,  80., 0],
     [ 18.,  22.,  37.,  56.,  68., 109., 103., 0],
     [ 24.,  35.,  55.,  64.,  81., 104., 113., 0],
     [ 49.,  64.,  78.,  87., 103., 121., 120., 0],
     [ 72.,  92.,  95.,  98., 112., 100., 103., 0]]

是否有一种简单的方法,最好不使用循环,例如'for','while','map'或列表理解?

谢谢您!

python arrays numpy indexing numpy-ndarray
1个回答
0
投票

您只可以切片分配给b,直到a的尺寸:

x, y = a.shape
b[:x, :y] = a

print(b)
array([[ 16.,  11.,  10.,  16.,  24.,  40.,  51.,   0.],
       [ 12.,  12.,  14.,  19.,  26.,  58.,  60.,   0.],
       [ 14.,  13.,  16.,  24.,  40.,  57.,  69.,   0.],
       [ 14.,  17.,  22.,  29.,  51.,  87.,  80.,   0.],
       [ 18.,  22.,  37.,  56.,  68., 109., 103.,   0.],
       [ 24.,  35.,  55.,  64.,  81., 104., 113.,   0.],
       [ 49.,  64.,  78.,  87., 103., 121., 120.,   0.],
       [ 72.,  92.,  95.,  98., 112., 100., 103.,   0.]])
© www.soinside.com 2019 - 2024. All rights reserved.