有没有一个漂亮的Python数据打印机?
交互地使用 python,有时需要显示一些任意复杂的数据结构的结果(如带有嵌入列表的列表等) 显示它们的默认方式只是一个巨大的线性转储,它会一遍又一遍地循环,您必须仔细解析才能阅读它。
有没有什么东西可以接受任何Python对象并以更合理的方式显示它。 例如,
[0, 1,
[a, b, c],
2, 3, 4]
而不是:
[0, 1, [a, b, c], 2, 3, 4]
我知道这不是一个很好的例子,但我想你明白了。
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.
Is there something that will take any python object and display it in a more rational manner. e.g.
[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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有时 YAML 对此很有用。
生产:
Somtimes YAML can be good for this.
Produces:
请注意,对于像我的示例这样的简短列表,pprint 实际上会将其全部打印在一行上。 然而,对于更复杂的结构,它可以很好地打印漂亮的数据。
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.
另一个不错的选择是使用 IPython,它是一个交互式环境,具有许多额外功能,包括自动漂亮的打印、制表符完成方法、轻松的 shell 访问等等。 它也非常容易安装。
IPython 教程
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 tutorial
除了
pprint.pprint
之外,pprint.pformat
对于制作可读的__repr__
也非常有用。 我的复杂__repr__
通常看起来像这样:In addition to
pprint.pprint
,pprint.pformat
is really useful for making readable__repr__
s. My complex__repr__
s usually look like so: