无需手动编写+-操作,如何生成含整数正负范围的NumPy数组?
Instead of manually writing out each addition/subtraction operation, we can leverage NumPy's broadcasting feature with a pre-defined offset array. This is cleaner, more scalable, and avoids repetitive code.
Step 1: Define the Offset Range
First, create an array of the offsets we need (-2, -1, 0, 1, 2) using np.arange—this is far more efficient than hardcoding each value:
import numpy as np offsets = np.arange(-2, 3) # Output: array([-2, -1, 0, 1, 2])
Step 2: Handle Single Integer Input
For a single integer (like a = np.array(5)), simply add the offsets to a. NumPy will automatically broadcast the scalar to match the offset array's shape, giving us the desired range:
a = np.array(5) result = a + offsets print(result) # Output: array([3, 4, 5, 6, 7])
Step 3: Handle Array of Integers
For an array input (like a = np.array([5, 16, 27])), reshape a to a 2D column array so broadcasting works across every element. Then flatten the result to get the concatenated output you need:
a = np.array([5, 16, 27]) result = (a[:, None] + offsets).flatten() print(result) # Output: array([ 3, 4, 5, 6, 7, 14, 15, 16, 17, 18, 25, 26, 27, 28, 29])
Why This Works
- Broadcasting: NumPy aligns the shape of
a[:, None](a 3x1 array) withoffsets(a 1x5 array) to perform element-wise addition for every combination, resulting in a 3x5 array of ranges for each input value. - Flattening: The
flatten()method converts the 2D array into a single 1D array, which is exactly equivalent to concatenating all individual ±2 ranges manually.
Scalability Bonus
If you ever need to adjust the range (e.g., expand to -3 to +3), you only need to modify the np.arange parameters instead of adding more manual operations:
offsets = np.arange(-3, 4) # Gives [-3,-2,-1,0,1,2,3]
This approach keeps your code DRY (Don't Repeat Yourself) and much easier to maintain as your needs change.
内容的提问来源于stack exchange,提问作者Roman

