我正在尝试制作一个程序,该程序将接收行列表并以网格形式打印出来。
我已经成功地将行列表转换为网格格式,但目前我无法以特定方式对齐行。
我想出了一个算法,但我不确定这是否是 pythonic 方式。
grid = [[21, 21, 21, 21, 21], [21, 42, 63, 84, 105], [21, 63, 126, 210, 315], [21, 84, 210, 420, 735], [21, 105, 315, 735, 1470]]
# grid[-1][-1]always the largest number in grid
# p is the number of digits of the largest number
p = len(str(grid[-1][-1]))
manipulated_grid = '\n'.join(' '.join(map(str, x)) for x in grid)
print(manipulated_grid)
# current output
21 21 21 21 21
21 42 63 84 105
21 63 126 210 315
21 84 210 420 735
21 105 315 735 1470
第一个目标是将第一行中的元素隔开。我打算给
(p - 1) * ' ' for the spacing between the elements in the first row.
例如,由于最大的数字是 1470,它的数字是 4,所以我希望第一行的元素之间有 3 个空格。
我尝试使用正则表达式模块,但我的努力最终以失败告终。我应该如何处理?
# current output
21 21 21 21 21
21 42 63 84 105
21 63 126 210 315
21 84 210 420 735
21 105 315 735 1470
# 1st objective
21 21 21 21 21
21 42 63 84 105
21 63 126 210 315
21 84 210 420 735
21 105 315 735 1470
第一行排成一行,现在我的第二个目标是将其他行中的所有元素右对齐到第一行。
# desired output
21 21 21 21 21
21 42 63 84 105
21 63 126 210 315
21 84 210 420 735
21 105 315 735 1470
我也一直在尝试使用 rjust() 函数,但我不知道如何将该函数应用到我的案例中。
最佳答案
在 python >= 3.6 中你可以这样做:
for row in grid:
print(' '.join(f'{item:4d}' for item in row))
并且(如评论中所述)如果您有较旧的 python,则可以通过这种方式使用字符串格式:
for row in grid:
print(' '.join('{:4d}'.format(item) for item in row))
如果您不想逐行打印网格行,可以这样做:
grid_str = '\n'.join(' '.join(f'{item:4d}' for item in row) for row in grid)
print(grid_str)
'{:3d}'
将为您的整数保留 3 个字符并将它们右对齐。
有关 python 字符串格式的更多信息:https://pyformat.info/ .
如果你不知道前面的宽度,你可以这样做:
width = len(str(max(n for row in grid for n in row)))
fmt = '{{:{}d}}'.format(width)
grid_str = '\n'.join(' '.join(fmt.format(item) for item in row) for row in grid)
print(grid_str)
对于更多选项,我还建议 tabulate
(如对您帖子的第一条评论)。
关于python - 右对齐网格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53293851/