You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从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:

  1. 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.
  2. 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.
  3. Efficiency: List operations (extend and 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:47:44