从9x9数独网格提取所有3x3子网格的Python算法优化咨询
Great question! Your current approach works, but using string concatenation to collect the numbers is indeed unnecessary and can be replaced with direct list operations that are more efficient and readable.
Here's a cleaner, more efficient version of your function that avoids string manipulation entirely:
def get_grids(grid): out = [] # Iterate over the top-left corner of each 3x3 block for i in range(0, 9, 3): for j in range(0, 9, 3): # Collect all elements in the current 3x3 block block = [] for row in grid[i:i+3]: block.extend(row[j:j+3]) out.append(block) return out
If you prefer a more concise one-liner using list comprehensions (which is also efficient), you can write:
def get_grids(grid): return [ [num for row in grid[i:i+3] for num in row[j:j+3]] for i in range(0, 9, 3) for j in range(0, 9, 3) ]
Key improvements over your original code:
- No string operations: We directly collect the integer values from the grid instead of converting to strings, concatenating, then converting back. This eliminates unnecessary overhead and makes the code more straightforward.
- Readability: The logic is clearer—we're explicitly slicing rows and columns to get each 3x3 block, which is easier to follow than nested loops over individual indices.
- Efficiency: List operations (
extendand list comprehensions) are generally faster than string concatenation for this kind of data collection.
Both versions will produce exactly the same output as your original function, passing your assertion tests, but in a more idiomatic Python way.
内容的提问来源于stack exchange,提问作者GAP2002
相关产品推荐
相关产品推荐

