参考资料:一文弄懂Python中的pprint模块
代码地址:https://github.com/SeafyLiang/Python_study/tree/master/basics

1、引言

pprint 的英文全称 Data pretty printer ,顾名思义就是让显示结果更加直观漂亮。
print()和 pprint()都是python的打印模块,功能基本一样,唯一的区别就是pprint()模块打印出来的数据结构更加完整,每行为一个数据结构,更加方便阅读打印输出结果。特别是对于特别长的数据打印,print()输出结果都在一行,不方便查看,而pprint()采用分行打印输出,所以对于数据结构比较复杂、数据长度较长的数据,适合采用pprint()打印方式。
在介绍完上述理论知识后,我们不妨来举个栗子吧!

2、使用背景

我们来看一个打印嵌套字典的例子,如下所示:

  1. d = {
  2. "apple": {"juice":4, "pie":5},
  3. "orange": {"juice":6, "cake":7},
  4. "pear": {"cake":8, "pie":9}
  5. }
  6. print(d)
  7. # {'apple': {'juice': 4, 'pie': 5}, 'orange': {'juice': 6, 'cake': 7}, 'pear': {'cake': 8, 'pie': 9}}
  8. for k,v in d.items():
  9. print(k, "->", v)
  10. # apple -> {'juice': 4, 'pie': 5}
  11. # orange -> {'juice': 6, 'cake': 7}
  12. # pear -> {'cake': 8, 'pie': 9}

3、pprint 大法好

有了上述的简短介绍,我们这里直接使用pprint来打印上述字典,样例代码如下:

  1. pprint(d)
  2. # {'apple': {'juice': 4, 'pie': 5},
  3. # 'orange': {'cake': 7, 'juice': 6},
  4. # 'pear': {'cake': 8, 'pie': 9}}

需要注意的是,pprint 以人类可读的格式很好地格式化了嵌套字典,而不需要像前面的示例中那样来编写for循环实现同样的功能。

4、设定输出宽度

在了解了pprint的入门示例后,我们来看看该函数的其他高级用法。这里我们不妨以一个三层嵌套字典为例来进行讲解,示例如下:

  1. d = {
  2. "apple": {
  3. "juice": {1:2, 3:4, 5:6},
  4. "pie": {1:3, 2:4, 5:7},
  5. },
  6. "orange": {
  7. "juice": {1:5, 2:3, 5:6},
  8. "cake": {5:4, 3:2, 6:5},
  9. },
  10. "pear": {
  11. "cake": {1:6, 6:1, 7:8},
  12. "pie": {3:5, 5:3, 8:7},
  13. }
  14. }

其实,在pprint函数中有一个参数width可以控制每行输出的宽度,直接使用pprint输出如下:

  1. pprint(d)
  2. # output
  3. {'apple': {'juice': {1: 2, 3: 4, 5: 6}, 'pie': {1: 3, 2: 4, 5: 7}},
  4. 'orange': {'cake': {3: 2, 5: 4, 6: 5}, 'juice': {1: 5, 2: 3, 5:6}},
  5. 'pear': {'cake': {1: 6, 6: 1, 7: 8}, 'pie': {3: 5, 5: 3, 8: 7}}}

将宽度设置为50,此时输出如下:

  1. pprint(d, width=50)
  2. # output:
  3. {'apple': {'juice': {1: 2, 3: 4, 5: 6},
  4. 'pie': {1: 3, 2: 4, 5: 7}},
  5. 'orange': {'cake': {3: 2, 5: 4, 6: 5},
  6. 'juice': {1: 5, 2: 3, 5: 6}},
  7. 'pear': {'cake': {1: 6, 6: 1, 7: 8},
  8. 'pie': {3: 5, 5: 3, 8: 7}}}

将宽度设置为30,此时输出如下:

  1. pprint(d, width=30)
  2. # output
  3. {'apple': {'juice': {1: 2,
  4. 3: 4,
  5. 5: 6},
  6. 'pie': {1: 3,
  7. 2: 4,
  8. 5: 7}},
  9. 'orange': {'cake': {3: 2,
  10. 5: 4,
  11. 6: 5},
  12. 'juice': {1: 5,
  13. 2: 3,
  14. 5: 6}},
  15. 'pear': {'cake': {1: 6,
  16. 6: 1,
  17. 7: 8},
  18. 'pie': {3: 5,
  19. 5: 3,
  20. 8: 7}}}

5、设定输出缩进

我们以下面这个字典为例来讲解缩进参数 indent 的作用:
将缩进设置为4时的输出如下:

  1. pprint(d, indent=4)
  2. # output
  3. { 'apple': {'juice': 4, 'pie': 5},
  4. 'orange': {'cake': 7, 'juice': 6},
  5. 'pear': {'cake': 8, 'pie': 9}}

将缩进设置为8时的输出如下:

  1. pprint(d, indent=8)
  2. # output
  3. { 'apple': {'juice': 4, 'pie': 5},
  4. 'orange': {'cake': 7, 'juice': 6},
  5. 'pear': {'cake': 8, 'pie': 9}}

5、总结

本文重点介绍了Python中的pprint模块,使用该模块可以提升我们减少我们编写代码的行数同时增加我们复杂数据结构输出的可读性。