当前位置: 首页 > news >正文

pprint:美观打印数据结构

文章目录

  • 一、pprint.pprint():美观化打印
  • 二、pprint.pformat():格式化成字符串表示
  • 三、pprint() 处理包含__repr__() 方法的类
  • 四、递归引用:Recursion on {typename} with id={number}
  • 五、depth 参数控制 pprint() 方法的输出深度
  • 六、width 参数控制 pprint() 方法的输出宽度
  • 七、compact 参数尝试在每一行上放置更多数据

pprint模块包含一个「美观打印机」,用于生成数据结构的美观视图。

本篇文章后续代码中均会使用到如下data变量数据:

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模块的pprint()方法可以美观化打印数据结构。该方法格式化一个对象,并把该对象作为参数传入,写至一个数据流(或者是默认的sys.stdout)。

from pprint import pprintprint(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', 'tu', 'v', 'x', 'y', 'z'])]pprint(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', 'tu', 'v', 'x', 'y', 'z'])]

二、pprint.pformat():格式化成字符串表示

使用pprint模块的pformat()方法将数据结构格式化成一个字符串表示,然后可以打印这个格式化的字符串或者写入日志。

import logging
from pprint import pformatlogging.basicConfig(# 将日志输出级别设置为 DEBUGlevel=logging.DEBUG,# 日志的输出格式为「级别名称(左对齐8字符)+ 日志消息」,-表示左对齐format='%(levelname)-8s %(message)s',
)logging.debug('Logging pformatted data')
formatted = pformat(data)
for line in formatted.splitlines():logging.debug(line.rstrip())>>> 输出结果:
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()方法底层使用的PrettyPrinter类可以处理定义了__repr__()方法的类。

from pprint import pprintclass node:def __init__(self, name, contents=[]):self.name = nameself.contents = contents[:]def __repr__(self):# repr()返回一个对象的“官方”字符串表示# 理想情况下,这个字符串是一个有效的 Python 表达式,能够用来重新创建这个对象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')]),
]
# 嵌套对象的表示形式由 PrettyPrinter 组合,以返回完整的字符串表示
pprint(trees)>>> 输出结果:
[node('node-1', []),node('node-2', [node('node-2-1', [])]),node('node-3', [node('node-3-1', [])])]

四、递归引用:Recursion on {typename} with id={number}

递归数据结构由指向原数据源的引用表示,形式为<Recursion on {typename} with id={number}>

from pprint import pprintlocal_data = ['a', 'b', 1, 2]
# 列表增加到其自身,这会创建一个递归引用
local_data.append(local_data)# id()函数用于获取列表对象的内存地址标识符
# 4306287424
print(id(local_data))
# ['a', 'b', 1, 2, <Recursion on list with id=4306287424>]
pprint(local_data)

五、depth 参数控制 pprint() 方法的输出深度

对于非常深的数据结构,可能不必输出所有的细节。使用depth参数可以控制pprint()方法对数据结构的输出深度,输出中未包含的层次用省略号表示。

from pprint import pprint# [(...), (...), (...), (...), (...)]
pprint(data, depth=1)
# [(1, {...}), (2, {...}), (3, [...]), (4, [...]), (5, [...])]
pprint(data, depth=2)

六、width 参数控制 pprint() 方法的输出宽度

可以在pprint()方法中使用参数width控制格式化文本的输出宽度,默认宽度是80列。注意,当宽度太小而无法完成格式化时,如果截断或转行会导致非法语法,那么便不会截断或转行。

from pprint import pprintfor width in [80, 5, 1]:print('WIDTH =', width)pprint(data, width=width)print()# >>> 输出结果:
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'])]WIDTH = 1
[(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 参数尝试在每一行上放置更多数据

compact布尔型参数(默认False)使得pprint()方法尝试在每一行上放置更多数据,而不是把复杂数据结构分解为多行。

注意:一个数据结构在一行上放不下时,就会分解;如果多个元素可以放置在一行上,就会合放。

from pprint import pprintprint('DEFAULT:')
pprint(data, compact=False)
print('\nCOMPACT:')
pprint(data, compact=True)>>> 输出结果:
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'])]
http://www.xdnf.cn/news/1426123.html

相关文章:

  • 基于单片机十六路抢答器系统Proteus仿真(含全部资料)
  • Qt::Q_INIT_RESOURCE用法
  • 前端性能优化实战:如何高效管理和加载图片、字体、脚本资源
  • 在 Qt 中:QString 好,还是 std::string 好?
  • 零售行业的 AI 革命:从用户画像到智能供应链,如何让 “精准营销” 不再是口号?
  • 响应式编程框架Reactor【9】
  • 2.充分条件与必要条件
  • 基本问题解决--舵机
  • 手把手教你搭建 UDP 多人聊天室(附完整源码)
  • 10.《基础知识探秘:DHCP地址分配员》
  • 打工人日报#20250901
  • nCode 后处理常见问题汇总
  • C++精选面试题集合(100份大厂面经提取的200+道真题)
  • 实现自己的AI视频监控系统-第三章-信息的推送与共享2
  • 【自记录】Ubuntu20.04下Python自编译
  • docker-nacos-v3
  • 在飞牛构建私有化协作环境GodoOS:集成文档、即时通讯、白板与思维导图!
  • 用只能以关键字指定和只能按位置传入的参数来设计清晰的接口(Effective Python 第25条)
  • Web知识的总结
  • Linux并发与竞争实验
  • Linux 下 MySQL 数据库定时备份脚本与 Crontab 配置
  • RK3588部署yolov8目标检测
  • Redis 的 SDS:像橡皮筋笔记本一样好用的字符串
  • 区块链存证中的隐私保护
  • C++ 用于运行时类型识别的typeinfo库使用指南
  • 基于STICS模型的黄土高原苹果园生态
  • 众擎机器人开源代码解读
  • 从物理模拟器和世界模型中学习具身智能
  • 【算法专题训练】17、双向链表
  • 开源项目硬核应用:AntPathMatcher实战