如何让numpy.savetxt生成的文本居中对齐?

3 投票
1 回答
1896 浏览
提问于 2025-04-17 19:55

我用一个小工具包来封装numpy.savetxt,这样可以自动生成标题名称,并且让输出的内容对齐得更好,便于阅读。如果你想要一个更简单的解决方案,可以看看这个回答

我想知道怎么指定宽度,并让输出的文本居中对齐,而不是像文档中所说的那样只是左对齐。

numpy.savetxt的文档中,我看到了一些信息:

Notes
-----
Further explanation of the `fmt` parameter
(``%[flag]width[.precision]specifier``):
flags:
    ``-`` : left justify

    ``+`` : Forces to preceed result with + or -.

    ``0`` : Left pad the number with zeros instead of space (see width).

width:
    Minimum number of characters to be printed. The value is not truncated
    if it has more characters.

文档中提到有一个更详细的资源在python迷你格式规范,但是那里的信息对于对齐来说并不适用。

各种对齐选项的含义如下:

Option  Meaning
'<'     Forces the field to be left-aligned within the available space (this is the default for most objects).
'>'     Forces the field to be right-aligned within the available space (this is the default for numbers).
'='     Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types.
'^'     Forces the field to be centered within the available space.

之所以不兼容,是因为savetxt不接受'^'作为有效的格式字符。有没有人能告诉我怎么在`numpy.savetxt`中指定格式,让输出居中对齐呢?

1 个回答

1

你可以使用 format 来组合更复杂的格式选项,包括居中的 '^' 标志:

import numpy as np
a = np.ones((3,3))*100
a[1,1]=111.12321
a[2,2]=1
np.savetxt('tmp.txt',a, fmt='{:*^10}'.format('%f'))

这样就可以得到:

****100.000000**** ****100.000000**** ****100.000000****
****100.000000**** ****111.123210**** ****100.000000****
****100.000000**** ****100.000000**** ****1.000000****

撰写回答