创建整齐的表格输出并将其以相同的方式保存到文本文件中的最佳方法是什么?
现在我正在使用以下代码将我的输出显示在IPython控制台上,该代码提供了如图(1)所示的输出。
outputLine = ["NIST line CG100 CG050 FactoryCal HMFW (nm)-original (SIGMA) WCalFunctionDerivatives"]
for n, line in enumerate(wlines, 1):
outputLine.append(" ".join(
[str(item) for item in [wlines[n-1],peaks[n-1].cg100(),
peaks[n-1].cgArb(0.5),
wavelengthToPixel(wlines[n-1], 500, wavep),
peaks[n-1].getHMFW() / prismpy.wcalfunctionDerivative(results.x, wlines[n-1]), peaks[n-1].getHMFWPixels(), prismpy.wcalfunctionDerivative(results.x, wlines[n-1])]]))
来自Mathematica背景,我可以使用哪些其他方法以整齐的表格格式显示相同的输出?提前谢谢。
答案 0 :(得分:1)
有一个python模块正是这样做的:tabulate
答案 1 :(得分:1)
如果您正在使用列表列表,则以下方法可能很有用:
def col_display(data, file):
widths = [0] * len(data[0])
for row in data:
widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)]
for row in data:
output = " ".join(["%-*s" % (widths[index], col) for index, col in enumerate(row)])
print(output)
file.write(output + '\n')
outputLine = ["NIST line", "CG100", "CG050", "FactoryCal", "HMFW (nm)-original", "(SIGMA)", "WCalFunctionDerivatives"]
wlines = [[123.1234567890] * 7] * 4
lines = [outputLine] + wlines
with open('output.txt', 'w') as f_output:
col_display(lines, f_output)
将显示以下内容,并创建具有相同内容的文本文件:
NIST line CG100 CG050 FactoryCal HMFW (nm)-original (SIGMA) WCalFunctionDerivatives
123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789
123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789
123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789
123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789