当前位置: 首页 > 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.dtcms.com/a/360982.html

相关文章:

  • Spring Boot 和 Spring Cloud 的原理和区别
  • Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
  • 单例模式
  • Day19_【机器学习—线性回归 (3)—回归模型评估方法】
  • 网站模板源代码 静态网页网站模板
  • VBA数据库解决方案第二十二讲:根据工作表数据生成数据库中数据表
  • 零售行业的 AI 革命:从用户画像到智能供应链,如何让 “精准营销” 不再是口号?
  • 百胜软件获邀出席第七届中国智慧零售大会,智能中台助力品牌零售数智变革
  • 百胜软件×OceanBase深度合作,赋能品牌零售数字化实践降本增效
  • leetcode 面试题17.19 消失的两个数字
  • Java学习笔记-反射(二)
  • 无公网IP,怎么实现远程调试与APP端api 接入?
  • 红楼梦 AI HTML 分析 - 好了歌
  • MySQL内置的各种单行函数
  • Kafka消息中间件安装配置
  • Ruoyi项目MyBatis升级MyBatis-Plus指南
  • sentinel异常处理机制
  • 2025机器人产业大洗牌:新兴初创企业的技术革命与崛起之路
  • 【Spring Cloud微服务】8.深度实战:微服务稳定性的守护神——Sentinel
  • Linux下usb设备驱动框架实现:定义核心结构体数据
  • 从Java全栈开发到微服务架构:一次真实的面试实录
  • leetcode算法刷题的第二十三天
  • GitLab 18.3 正式发布,更新多项 DevOps、CI/CD 功能【一】
  • Linux上perf工具的使用-基础采样
  • 云端虚拟云手机该如何进行使用?
  • 高并发场景下的热点数据处理:从预热到多级缓存的性能优化实践
  • 云手机和云游戏之间有着哪些区别?
  • 手机版碰一碰发视频源码搭建,技术实现与实操指南
  • 基于大数据的京东手机销售数据 可视化分析设计与开发03446原创的定制程序,java、PHP、python、C#小程序、文案全套、毕设程序定制、成品等
  • 【音视频】WebRTC QoS 概述