python 数据有漂亮的打印机吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/91810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 19:29:23  来源:igfitidea点击:

Is there a pretty printer for python data?

pythonprettify

提问by Ferruccio

Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.) The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it.

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

Is there something that will take any python object and display it in a more rational manner. e.g.

有没有什么东西可以接受任何python对象并以更合理的方式显示它。例如

[0, 1,
    [a, b, c],
    2, 3, 4]

instead of:

代替:

[0, 1, [a, b, c], 2, 3, 4]

I know that's not a very good example, but I think you get the idea.

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

回答by Greg Hewgill

from pprint import pprint
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
pprint(a)

Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.

请注意,对于像我的示例这样的简短列表, pprint 实际上会将其全部打印在一行上。然而,对于更复杂的结构,它在漂亮的打印数据方面做得很好。

回答by rjmunro

Somtimes YAMLcan be good for this.

有时,YAML对此很有用。

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

Produces:

产生:

- 0
- 1
- [a, b, c]
- 2
- 3
- 4

回答by AdamKG

In addition to pprint.pprint, pprint.pformatis really useful for making readable __repr__s. My complex __repr__s usually look like so:

除了pprint.pprint,pprint.pformat对于制作可读的__repr__s真的很有用。我的复杂__repr__s 通常看起来像这样:

def __repr__(self):
    from pprint import pformat

    return "<ClassName %s>" % pformat({"attrs":self.attrs,
                                       "that_i":self.that_i,
                                       "care_about":self.care_about})

回答by Gregg Lind

Another good option is to use IPython, which is an interactive environment with a lot of extra features, including automatic pretty printing, tab-completion of methods, easy shell access, and a lot more. It's also very easy to install.

另一个不错的选择是使用IPython,这是一个交互式环境,具有许多额外功能,包括自动漂亮打印、方法的制表符完成、轻松的外壳访问等等。它也很容易安装。

IPython tutorial

IPython教程