是否有一个漂亮的python数据打印机?

Fer*_*cio 17 python prettify

以交互方式使用python,有时需要显示一些结果,这是一些任意复杂的数据结构(如带有嵌入列表的列表等).显示它们的默认方式只是一个大规模的线性转储,它只是一遍又一遍地包装你有仔细解析阅读它.

有什么东西可以采取任何python对象并以更合理的方式显示它.例如

[0, 1,
    [a, b, c],
    2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

代替:

[0, 1, [a, b, c], 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

我知道这不是一个很好的例子,但我认为你明白了.

Gre*_*ill 26

from pprint import pprint
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
pprint(a)
Run Code Online (Sandbox Code Playgroud)

请注意,对于像我的例子这样的简短列表,pprint实际上会在一行上打印出来.但是,对于更复杂的结构,它可以很好地打印数据.


rjm*_*nro 10

SOMtimes YAML可能对此有好处.

import yaml
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
print yaml.dump(a)
Run Code Online (Sandbox Code Playgroud)

生产:

- 0
- 1
- [a, b, c]
- 2
- 3
- 4
Run Code Online (Sandbox Code Playgroud)


Ada*_*mKG 8

除此之外pprint.pprint,pprint.pformat对于制作可读的__repr__s 非常有用.我的情结__repr__通常如下:

def __repr__(self):
    from pprint import pformat

    return "<ClassName %s>" % pformat({"attrs":self.attrs,
                                       "that_i":self.that_i,
                                       "care_about":self.care_about})
Run Code Online (Sandbox Code Playgroud)