在二维数组中查找指定值并将其位置存入另一二维数组
Alright, let's walk through how to solve this problem—scanning a 2D data array for a specific value, grabbing each occurrence's row and column offsets, and storing those positions one after another in the locations 2D array. Here's a clear, step-by-step breakdown with code examples.
The core idea is straightforward: iterate over every element in the 2D data array, check if it matches your target search value, and whenever it does, record the row and column indices (offsets) as a new row in the locations array.
Step-by-Step Implementation
We'll use Python for the example since it’s intuitive for array operations, but the logic translates easily to other languages like JavaScript, Java, or C#.
Set up your initial variables
Start with an emptylocationsarray to hold the matched positions, and define your target search value.Loop through rows with row indices
Useenumerate()to loop through each row indata—this gives you both the row index (offset) and the row itself in one go.Loop through elements in each row
For each row, loop through its elements again withenumerate()to get the column index (offset) for every element.Check for matches and store positions
If the current element equals your search value, append the[row_index, column_index]pair as a new row tolocations.
Full Code Example
# Sample 2D data array (replace with your actual data) data = [ [10, 20, 30, 20], [40, 50, 20, 60], [70, 80, 90, 100] ] search_value = 20 locations = [] # Iterate through every element in the 2D array for row_offset, row in enumerate(data): for col_offset, element in enumerate(row): if element == search_value: # Add the position as a new row in locations locations.append([row_offset, col_offset]) # Print the results to verify print("Matched positions (row offset, column offset):") for position in locations: print(f"Row: {position[0]}, Column: {position[1]}")
Output
Matched positions (row offset, column offset): Row: 0, Column: 1 Row: 0, Column: 3 Row: 1, Column: 2
Key Notes to Consider
- Zero vs One-Based Offsets: The example uses zero-based indices (standard in most programming languages). If you need one-based positions (like row 1 instead of row 0), just add 1 to
row_offsetandcol_offsetwhen appending tolocations. - Language Adaptations: For JavaScript, you’d use nested
forloops withi(row index) andj(column index), then push[i, j]tolocationswhen a match is found. The logic stays identical—only the syntax changes. - Edge Cases: If
datais empty or the search value doesn’t exist,locationswill remain empty. You might want to add a check for this (e.g.,if not locations: print("No matches found!")) to handle those scenarios gracefully.
内容的提问来源于stack exchange,提问作者user9154422

