【问题标题】:Tabular display of output输出的表格显示
【发布时间】:2015-10-13 13:32:04
【问题描述】:

创建整洁的表格输出并以相同的方式将其保存到文本文件中的最佳方法是什么?

现在我正在 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 背景,我可以使用哪些其他方法以简洁的表格格式显示相同的输出?提前致谢。

【问题讨论】:

  • 如果您要对此数据进行任何分析,您可能需要查看pandas,它会将输出数据制成表格,但其优势在于分析。
  • @AChampion :无需对此数据进行进一步分析。最终结果应如图所示。不过会检查熊猫。你的意思是 DataFrame(pandas) 吗?
  • 是的,DataFrame 会保存数据并自动转换为字符串并在输出上制表。但这可能只是为了格式化而大材小用。虽然另一个 SO'er 说“来格式化,留下来分析”,我在这里附和。

标签: python python-2.7 output


【解决方案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

【讨论】:

    【解决方案2】:

    有一个 python 模块正是这样做的:tabulate

    【讨论】:

      猜你喜欢
      • 2020-08-01
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 2014-04-12
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多