求二维数组对称元素的扁平化索引——以5×5 NumPy数组为例
Let's break down how to solve this problem clearly. First, let's align on what "square symmetry relative to the center" means here: for any element at the 2D position (row, col) in an n×m array, its symmetric counterpart sits at (n-1 - row, m-1 - col). Our goal is to convert these 2D position pairs into their 1D flattened indices (using NumPy's default row-major/C-order) and collect all unique, non-duplicate pairs.
Step 1: 2D to 1D Index Conversion Basics
For a row-major flattened array (the default when using flatten() or ravel() in NumPy), the 1D index of a 2D position (row, col) is calculated as:
flat_index = row * m + col
Where m is the number of columns in the original array.
Step 2: Handle Edge Cases
- If both
n(rows) andm(columns) are odd, the center element's symmetric position is itself. We'll skip adding this element to our pair list since it doesn't form a pair with another distinct element. - If either
normis even, every element has a unique symmetric counterpart, so all pairs will consist of two different indices.
Step 3: General Function Implementation
Here's a Python function using NumPy that works for any n×m array:
import numpy as np def get_symmetric_index_pairs(n, m): # Generate all 2D coordinates in the array rows, cols = np.meshgrid(np.arange(n), np.arange(m), indexing='ij') rows = rows.flatten() cols = cols.flatten() # Calculate symmetric coordinates for each position sym_rows = n - 1 - rows sym_cols = m - 1 - cols # Convert original and symmetric positions to flattened indices original_indices = rows * m + cols sym_indices = sym_rows * m + sym_cols # Collect unique pairs (avoid duplicate reverse pairs like (a,b) and (b,a)) unique_pairs = [] seen_pairs = set() for idx, sym_idx in zip(original_indices, sym_indices): # Only add pairs where the first index is smaller than the second if idx < sym_idx and (idx, sym_idx) not in seen_pairs: unique_pairs.append((idx, sym_idx)) seen_pairs.add((idx, sym_idx)) return unique_pairs
Step 4: Test with a 5×5 Array
Let's test this function with your 5×5 example to verify:
pairs_5x5 = get_symmetric_index_pairs(5, 5) print(pairs_5x5[:5]) # Print first 5 pairs # Output: [(0, 24), (1, 23), (2, 22), (3, 21), (4, 20)]
The center element of the 5×5 array is at flattened index 12 (2D position (2,2)), and since its symmetric index is also 12, it's excluded from the pair list as expected.
How It Works
- We use
np.meshgridto generate every possible row and column coordinate in the array. - For each coordinate, we compute its symmetric counterpart by subtracting the original row/column from
n-1/m-1. - We convert both original and symmetric coordinates to their flattened 1D indices.
- We iterate through the index pairs, only keeping pairs where the first index is smaller than the second—this ensures we don't add duplicate reverse pairs (like (24,0) after already adding (0,24)).
内容的提问来源于stack exchange,提问作者Sterling Butters

