3.11. pprint — 格式化输出数据结构 | 数据结构 |《python 3 标准库实例教程》| python 技术论坛-380玩彩网官网入口
用途:美观地打印数据结构
pprint
模块能够美观地对数据结构进行格式化。这种格式可以被解析器解析,也很易读。输出尽可能地保持在一行,需要分拆到多行时会有缩进表示。
本节的示例都依赖下面的 pprint_data.py
。
pprint_data.py
data = [
(1, {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}),
(2, {'e': 'e', 'f': 'f', 'g': 'g', 'h': 'h',
'i': 'i', 'j': 'j', 'k': 'k', 'l': 'l'}),
(3, ['m', 'n']),
(4, ['o', 'p', 'q']),
(5, ['r', 's', 't''u', 'v', 'x', 'y', 'z']),
]
打印
使用该模块最简单的方法是通过 pprint()
函数。
pprint_pprint.py
from pprint import pprint
from pprint_data import data
print('print:')
print(data)
print()
print('pprint:')
pprint(data)
pprint()
格式化对象并将结果写入作为参数传入的数据流中(默认为 sys.stdout
)。
$ python3 pprint_pprint.py
print:
[(1, {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}), (2, {'e': 'e', 'f':
'f', 'g': 'g', 'h': 'h', 'i': 'i', 'j': 'j', 'k': 'k', 'l': 'l'}), (
3, ['m', 'n']), (4, ['o', 'p', 'q']), (5, ['r', 's', 'tu', 'v', 'x',
'y', 'z'])]
pprint:
[(1, {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}),
(2,
{'e': 'e',
'f': 'f',
'g': 'g',
'h': 'h',
'i': 'i',
'j': 'j',
'k': 'k',
'l': 'l'}),
(3, ['m', 'n']),
(4, ['o', 'p', 'q']),
(5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]
格式化
如果需要格式化数据结构但不直接写入数据流(例如,记入日志),可以使用 pformat()
来构造格式化字符串。
pprint_pformat.py
import logging
from pprint import pformat
from pprint_data import data
logging.basicconfig(
level=logging.debug,
format='%(levelname)-8s %(message)s',
)
logging.debug('logging pformatted data')
formatted = pformat(data)
for line in formatted.splitlines():
logging.debug(line.rstrip())
然后可以打印这个格式化字符串或将其记入日志。
$ python3 pprint_pformat.py
debug logging pformatted data
debug [(1, {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}),
debug (2,
debug {'e': 'e',
debug 'f': 'f',
debug 'g': 'g',
debug 'h': 'h',
debug 'i': 'i',
debug 'j': 'j',
debug 'k': 'k',
debug 'l': 'l'}),
debug (3, ['m', 'n']),
debug (4, ['o', 'p', 'q']),
debug (5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]
类
pprint()
也可以对类对象进行使用,如果该类定义了 __repr__()
方法。
pprint_arbitrary_object.py
from pprint import pprint
class node:
def __init__(self, name, contents=[]):
self.name = name
self.contents = contents[:]
def __repr__(self):
return (
'node(' repr(self.name) ', '
repr(self.contents) ')'
)
trees = [
node('node-1'),
node('node-2', [node('node-2-1')]),
node('node-3', [node('node-3-1')]),
]
pprint(trees)
对于嵌套的对象,结果字符串也会被相应地组合起来。
$ python3 pprint_arbitrary_object.py
[node('node-1', []),
node('node-2', [node('node-2-1', [])]),
node('node-3', [node('node-3-1', [])])]
递归
对于递归的数据结构,结果中会包含对数据源的引用,格式为
。
pprint_recursion.py
from pprint import pprint
local_data = ['a', 'b', 1, 2]
local_data.append(local_data)
print('id(local_data) =>', id(local_data))
pprint(local_data)
在本例中,列表 local_data
追加了自己,形成了递归引用。
$ python3 pprint_recursion.py
id(local_data) => 4358913288
['a', 'b', 1, 2, ]
限制嵌套输出
对于嵌套层数很多的数据结构,我们也许不希望输出包含太多细节,因为数据可能没有被正确地格式化,格式化后的文本可能太大,或者某些数据是无关的。
pprint_depth.py
from pprint import pprint
from pprint_data import data
pprint(data, depth=1)
pprint(data, depth=2)
depth
参数用来控制对于嵌套数据结构输出的递归深度,输出中未包含的层级以省略号表示。
$ python3 pprint_depth.py
[(...), (...), (...), (...), (...)]
[(1, {...}), (2, {...}), (3, [...]), (4, [...]), (5, [...])]
控制输入宽度
格式化文本的输出默认宽度是80列,可以使用 pprint()
的 width
参数来调整。
pprint_width.py
from pprint import pprint
from pprint_data import data
for width in [80, 5]:
print('width =', width)
pprint(data, width=width)
print()
如果宽度太小无法容纳格式化后的数据结构时,输出不会截断或换行,这样可以避免引入无效的语法。
$ python3 pprint_width.py
width = 80
[(1, {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}),
(2,
{'e': 'e',
'f': 'f',
'g': 'g',
'h': 'h',
'i': 'i',
'j': 'j',
'k': 'k',
'l': 'l'}),
(3, ['m', 'n']),
(4, ['o', 'p', 'q']),
(5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]
width = 5
[(1,
{'a': 'a',
'b': 'b',
'c': 'c',
'd': 'd'}),
(2,
{'e': 'e',
'f': 'f',
'g': 'g',
'h': 'h',
'i': 'i',
'j': 'j',
'k': 'k',
'l': 'l'}),
(3,
['m',
'n']),
(4,
['o',
'p',
'q']),
(5,
['r',
's',
'tu',
'v',
'x',
'y',
'z'])]
compact
标记会使 pprint()
尽可能在一行容纳更多的数据,而不是将复杂的数据结构多行输出。
pprint_compact.py
from pprint import pprint
from pprint_data import data
print('default:')
pprint(data, compact=false)
print('\ncompact:')
pprint(data, compact=true)
当数据结构不适合在一行输出时,它会被拆分(如列表中的第二项)。如果多个元素可以容纳在一行时,它们就会被合并在一行输出,如列表中的第三项和第四项。
$ python3 pprint_compact.py
default:
[(1, {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}),
(2,
{'e': 'e',
'f': 'f',
'g': 'g',
'h': 'h',
'i': 'i',
'j': 'j',
'k': 'k',
'l': 'l'}),
(3, ['m', 'n']),
(4, ['o', 'p', 'q']),
(5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]
compact:
[(1, {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}),
(2,
{'e': 'e',
'f': 'f',
'g': 'g',
'h': 'h',
'i': 'i',
'j': 'j',
'k': 'k',
'l': 'l'}),
(3, ['m', 'n']), (4, ['o', 'p', 'q']),
(5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]
参见
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 cc 协议,如果我们的工作有侵犯到您的权益,请及时联系380玩彩网官网入口。