【问题标题】:How do I print a list of doubles nicely in python?如何在 python 中很好地打印双打列表?
【发布时间】:2014-04-06 11:49:22
【问题描述】:

到目前为止,我有:

x=[0.0, 1.2135854798749774, 1.0069824713281044, 0.5141246736157659, -0.3396344921640888, -0.33926090064512615, 0.4877599543804152, 0.0]

print ' '.join(["%.2f" % s for s in x])

产生:

0.00 1.21 1.01 0.51 -0.34 -0.34 0.49 0.00

问题在于 -0.34 比 0.51 长一个字符,这在打印多个列表时会产生参差不齐的左边缘。

有更好的想法吗?

我想要:

0.00 1.21 1.01 0.51 -0.34 -0.34 0.49 0.00
0.00 1.21 1.01 0.51 0.34 0.34 0.49 0.00
0.00 1.21 -1.01 -0.51 -0.34 -0.34 -0.49 0.00

变成:

0.00 1.21  1.01  0.51 -0.34 -0.34  0.49 0.00
0.00 1.21  1.01  0.51  0.34  0.34  0.49 0.00
0.00 1.21 -1.01 -0.51 -0.34 -0.34 -0.49 0.00

如果有一些内置或标准库的方式来做这件事会更好,因为print ' '.join(["%.2f" % s for s in x]) 需要输入很多内容。

【问题讨论】:

  • 你试过"% .2f"(注意:空格)吗?
  • 这就是我一直在寻找的答案!可惜不能接受评论。谢谢。
  • 如果你认为你找到了答案;你可以post it and accept it
  • 是的,但我想感谢您。你发的话我就采纳,否则我自己发。

标签: python printing format


【解决方案1】:

只需相应地调整正数和负数的填充:

''.join(["  %.2f" % s if s >= 0 else " %.2f" % s for s in x]).lstrip()

【讨论】:

    【解决方案2】:

    使用rjustljust

    x=[0.0, 1.2135854798749774, 1.0069824713281044, 0.5141246736157659, -0.3396344921640888, -0.33926090064512615, 0.4877599543804152, 0.0]
    
    print ' '.join([("%.2f"%s).ljust(5) for s in x])
    

    【讨论】:

      【解决方案3】:

      试试这个:print ' '.join(["%5.2f" % s for s in x]),字符串“%5.2f”中的数字 5 指定了最大字段宽度。它与 C 中的转换规范兼容。

      【讨论】:

        【解决方案4】:

        你试过"% .2f"(注意:空格)吗? ——J.F.塞巴斯蒂安

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-25
          • 2010-12-04
          • 2020-04-08
          • 1970-01-01
          • 2019-10-07
          • 1970-01-01
          • 2016-05-11
          • 2023-04-02
          相关资源
          最近更新 更多