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

如何使Numpy数组每行与下方行均匀对齐以优化数独输出

解决Numpy数独数组打印对齐问题

要让Numpy存储的数独数据打印时各行对齐、间隔均匀,你可以通过自定义格式化逻辑实现,以下是两种可行方案:

方案一:自定义打印函数(推荐,样式更灵活)

遍历数组每行,将每个元素格式化为固定宽度,确保对齐效果:

import numpy as np

# 你的数独数组
sudoku_board = np.array([
    [6, 5, 3, 189, 7, 2, 4, 89, 189],
    [1789, 1789, 89, 135689, 3569, 4, 56789, 2, 136789],
    [1789, 4, 2, 135689, 3569, 3569, 56789, 356789, 136789],
    [2, 369, 7, 3569, 4, 8, 569, 1, 369],
    [13589, 13689, 4, 3569, 2, 35679, 56789, 356789, 36789],
    [3589, 3689, 5689, 3569, 1, 35679, 2, 356789, 4],
    [5789, 6789, 1, 2, 5689, 569, 3, 4, 6789],
    [35789, 36789, 5689, 4, 5689, 1569, 16789, 6789, 2],
    [4, 2, 689, 7, 3689, 1369, 1689, 689, 5]
])

def print_sudoku(board):
    # 动态计算元素最大长度,适配所有数据
    max_len = max(len(str(num)) for row in board for num in row)
    # 每个元素宽度设为最大长度+1,预留间隔
    elem_width = max_len + 1
    for row in board:
        # 右对齐格式化每行元素,保证数字对齐
        formatted_row = ''.join(f"{num:>{elem_width}}" for num in row)
        print(formatted_row)

# 调用打印
print_sudoku(sudoku_board)

方案二:修改Numpy打印选项

直接设置Numpy全局打印格式,快速实现对齐:

import numpy as np

sudoku_board = np.array([...])  # 替换为你的数独数组
# 设置所有元素右对齐占6位(可根据实际数据调整宽度)
np.set_printoptions(formatter={'all': lambda x: f"{x:>6}"})
print(sudoku_board)

效果示例

运行后输出会整齐对齐,类似:

6     5     3   189     7     2     4    89   189
   1789   1789    89 135689   3569     4  56789     2 136789
   1789     4     2 135689   3569   3569  56789 356789 136789
     2    369     7   3569     4     8    569     1    369
  13589  13689     4   3569     2   35679  56789 356789  36789
   3589   3689   5689   3569     1   35679     2 356789     4
   5789   6789     1     2   5689    569     3     4   6789
  35789  36789   5689     4   5689   1569  16789   6789     2
     4     2    689     7   3689   1369   1689    689     5

内容的提问来源于stack exchange,提问作者Bee Stevens

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 20:24:50