如何基于指定一维numpy数组循环访问10×10二维numpy数组的切片?
Got it, let's work through this problem together. Here's exactly how you can loop through your 1D numpy array to access the specified slices of your 10x10 2D array:
Step 1: Understand the Pair Logic
You have a 10-element 1D array, and need 10 loops total. Each loop uses:
- The current element as the start index for the slice
- The next element (wrapping back to the first element for the 10th loop) as the end index
Step 2: Basic Implementation (Standard Slices)
First, here's a straightforward version that works when the start index is less than the end index. We'll handle edge cases where start > end next.
import numpy as np # Your input 1D array one_d_array = np.array([1, 3, 8, 6, 0, 2, 4, 5, 9, 7]) # Example 10x10 2D array (replace this with your actual array) two_d_array = np.arange(100).reshape(10, 10) # Loop through each element and its consecutive pair (wrap around at the end) for loop_num in range(len(one_d_array)): start_idx = one_d_array[loop_num] # Get the next element, wrap to the first element if we're at the last index end_idx = one_d_array[(loop_num + 1) % len(one_d_array)] # Access the slice of the 2D array (this gets rows from start_idx to end_idx-1) slice_output = two_d_array[start_idx:end_idx] print(f"Loop {loop_num + 1}: Start={start_idx}, End={end_idx}") print("Slice Result:\n", slice_output, "\n")
Step 3: Handle Reverse Slice Cases
Notice that some pairs (like 8 and 6, 9 and 7) have a start index greater than the end index. The standard numpy slice will return an empty array here because slices only work in ascending order by default. If you want to wrap around from the end of the 2D array to the start in these cases, use np.r_ to concatenate the two parts of the slice:
import numpy as np one_d_array = np.array([1, 3, 8, 6, 0, 2, 4, 5, 9, 7]) two_d_array = np.arange(100).reshape(10, 10) for loop_num in range(len(one_d_array)): start_idx = one_d_array[loop_num] end_idx = one_d_array[(loop_num + 1) % len(one_d_array)] if start_idx < end_idx: # Normal ascending slice slice_output = two_d_array[start_idx:end_idx] else: # Wrap around: take rows from start_idx to end of array, then 0 to end_idx slice_output = two_d_array[np.r_[start_idx:10, 0:end_idx]] print(f"Loop {loop_num + 1}: Start={start_idx}, End={end_idx}") print("Slice Result:\n", slice_output, "\n")
Key Notes
- If you need to slice columns instead of rows, just modify the slice to
two_d_array[:, start_idx:end_idx](add the colon before the slice range). - The
(loop_num + 1) % len(one_d_array)trick ensures the 10th loop uses the last element (7) and the first element (1) as its pair, completing the cycle.
内容的提问来源于stack exchange,提问作者Will.S89

