如何用单行代码将Numpy 5×5全1数组内部元素设为0?
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

