You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用单行代码将Numpy 5×5全1数组内部元素设为0?

How to create a 5x5 bordered array (1s on edges, 0s inside) with a single NumPy line?

Absolutely! You can achieve this in a single line of NumPy code, and you don’t need the inner() function here (that’s meant for inner product calculations, not slicing arrays to modify regions). Here are a couple of straightforward approaches:

1. Modify your existing np.ones array in one line

If you already have a = np.ones([5,5]), use array slicing to target the inner elements and set them to 0 in a single statement:

a[1:-1, 1:-1] = 0

This works because 1:-1 selects all rows/columns except the first and last—exactly the inner 3x3 elements we want to zero out.

2. Create the final array in a single line (no prior initialization)

If you want to skip the initial np.ones step and build the array directly, use np.pad() to wrap a 3x3 zero array with a 1-element border of 1s:

a = np.pad(np.zeros((3,3)), pad_width=1, mode='constant', constant_values=1)

Either way, you’ll get your desired output:

array([[1., 1., 1., 1., 1.],
       [1., 0., 0., 0., 1.],
       [1., 0., 0., 0., 1.],
       [1., 0., 0., 0., 1.],
       [1., 1., 1., 1., 1.]])

To clarify why inner() isn’t suitable here: np.inner() computes dot products between 1D arrays or sums over the last axes for higher dimensions—this has nothing to do with selecting or modifying the inner region of a 2D array. Slicing is the right tool for this job!

内容的提问来源于stack exchange,提问作者Sparker0i

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:13:31