如何基于向量实现n维数组左上角子数组的自动切片?
Great question! When working with n-dimensional arrays (like the NumPy-style array in your example), you don’t need to manually write out slice ranges for every dimension—Python’s unpacking and generator expressions make this trivial and scalable.
Core Idea
The key is to convert your vector v_n into a tuple of slice objects, where each slice corresponds to 0:v_n[i] for the i-th dimension. NumPy arrays (and most array-like libraries) accept tuples of slices as indexers, which lets you dynamically generate the slice for any number of dimensions.
Step-by-Step Implementation
Let’s use NumPy (since your example aligns with its syntax) to demonstrate:
- First, import NumPy and define your n-dimensional array and dimension vector:
import numpy as np # Example 3D array (adjust dimensions as needed) A_3 = np.arange(5*6*7).reshape(5, 6, 7) # Vector specifying the upper bounds for each dimension v_3 = [2, 3, 4]
- Generate the dynamic slice tuple:
# Create a slice(0, v) for each value in v_n, then pack into a tuple slice_indices = tuple(slice(0, dim_size) for dim_size in v_3)
- Apply the slice to your array:
sublist = A_3[slice_indices]
- Verify the result—its shape will match
v_n:
print(sublist.shape) # Output: (2, 3, 4)
Testing with Your Original 2D Example
For your original 2D array A and vector v=[10, 3], this method works exactly as expected:
# Your original 2D array A = np.array([ [1.,2.,3.,0.,0.,0.,0.], [4.,5.,6.,0.,0.,0.,0.], [7.,8.,9.,0.,0.,0.,0.], [10.,11.,12.,0.,0.,0.,0.], [13.,14.,15.,0.,0.,0.,0.], [16.,17.,18.,0.,0.,0.,0.], [19.,20.,21.,0.,0.,0.,0.], [22.,23.,24.,0.,0.,0.,0.], [25.,26.,27.,0.,0.,0.,0.], [28.,29.,30.,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.] ]) v = [10, 3] slice_indices = tuple(slice(0, dim) for dim in v) result = A[slice_indices] # Result is exactly the 10x3 upper-left subarray you wanted
Optional: Add Dimension Validation
To avoid errors if v_n doesn’t match the number of dimensions in A_n, add a quick check:
if len(v_n) != A_n.ndim: raise ValueError("Vector v_n must have the same length as the number of dimensions in A_n")
Why This Works
NumPy’s array indexing system natively supports tuple-based indexers. By generating a slice for each dimension dynamically, you avoid writing repetitive code like A_n[0:v1, 0:v2, 0:v3, ...]—this scales seamlessly to 1D, 2D, 10D, or any number of dimensions.
内容的提问来源于stack exchange,提问作者Jack Rolph

