pprint 模組(漂亮列印器)


pprint 模組 (lib/pprint.py) 是 Python 標準庫的一部分,與標準 Python 發行版一起分發。pprint 代表漂亮列印器 (pretty printer)。pprint 模組的功能使 Python 資料結構的外觀更美觀。任何可以被 Python 直譯器正確解析的資料結構都可以被優雅地格式化。格式化的表示式儘可能保持在一行,但如果長度超過格式化的 width 引數,則會分成多行。pprint 輸出的一個獨特之處在於,字典在顯示錶示形式被格式化之前會自動排序。

pprint 模組包含 PrettyPrinter 類的定義。其建構函式採用以下格式:

pprint.PrettyPrinter(indent, width, depth, stream, compact)

indent 引數定義每個遞迴級別新增的縮排。預設為 1。

width 引數預設為 80。期望的輸出受此值限制。如果長度大於 width,則會分成多行。

depth 引數控制要列印的級別數。

stream 引數預設為 std.out——預設輸出裝置。它可以採用任何流物件,例如檔案。

compact 引數預設為 False。如果為 True,則只顯示可在 width 內調整的資料。

PrettyPrinter 類定義了以下方法:

**pprint()** - 列印 PrettyPrinter 物件的格式化表示

**pformat()** - 返回物件的格式化表示,基於建構函式的引數。

以下示例演示了 PrettyPrinter 類的簡單用法。

import pprint
students = {"Dilip":["English", "Maths", "Science"],
   "Raju":{"English":50,"Maths":60, "Science":70},
   "Kalpana":(50,60,70)}
pp = pprint.PrettyPrinter()
print ("normal print output")
print (students)
print ("----")
print ("pprint output")
pp.pprint(students)

輸出顯示了普通列印和漂亮列印。

normal print output
{'Dilip': ['English', 'Maths', 'Science'], 'Raju': {'English': 50, 'Maths': 60, 'Science': 70}, 'Kalpana': (50, 60, 70)}
----
pprint output
{'Dilip': ['English', 'Maths', 'Science'],
'Kalpana': (50, 60, 70),
'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}

pprint 模組還定義了與 PrettyPrinter 方法對應的便利函式 pprint() 和 pformat()。下面的示例使用了 pprint() 函式。

from pprint import pprint
students = {"Dilip":["English", "Maths", "Science"],
"Raju":{"English":50,"Maths":60, "Science":70},
"Kalpana":(50,60,70)}
print ("normal print output")
print (students)
print ("----")
print ("pprint output")
pprint (students)

下一個示例使用 pformat() 方法和 pformat() 函式。要使用 pformat() 方法,首先要設定 PrettyPrinter 物件。在這兩種情況下,格式化的表示都使用普通的 print() 函式顯示。

import pprint
students = {"Dilip":["English", "Maths", "Science"],
"Raju":{"English":50,"Maths":60, "Science":70},
"Kalpana":(50,60,70)}
print ("using pformat method")
pp = pprint.PrettyPrinter()
string = pp.pformat(students)
print (string)
print ('------')
print ("using pformat function")
string = pprint.pformat(students)
print (string)

以下是上述程式碼的輸出

using pformat method
{'Dilip': ['English', 'Maths', 'Science'],
'Kalpana': (50, 60, 70),
'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}
------
using pformat function
{'Dilip': ['English', 'Maths', 'Science'],
'Kalpana': (50, 60, 70),
'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}

漂亮列印器也可以與自定義類一起使用。在類中重寫了 __repr__() 方法。當使用 repr() 函式時,會呼叫 __repr__() 方法。它是 Python 物件的官方字串表示。當我們使用物件作為 print() 函式的引數時,它會列印 repr() 函式的返回值。

在下面的示例中,__repr__() 方法返回 player 物件的字串表示

import pprint
class player:
def __init__(self, name, formats = [], runs = []):
self.name = name
self.formats = formats
self.runs = runs
def __repr__(self):
dct = {}
dct[self.name] = dict(zip(self.formats,self.runs))
return (repr(dct))
l1 = ['Tests','ODI','T20']
l2 = [[140, 45, 39],[15,122,36,67, 100, 49],[78,44, 12, 0, 23, 75]]
p1 = player("virat",l1,l2)
pp = pprint.PrettyPrinter()
pp.pprint(p1)

上述程式碼的輸出為:

{'virat': {'Tests': [140, 45, 39], 'ODI': [15, 122, 36, 67, 100, 49], 'T20': [78, 44, 12, 0, 23, 75]}}

使用 pprint 處理遞迴資料結構

當我們嘗試使用 pprint 列印遞迴物件時,只顯示第一個表示,對於後續的遞迴,只打印其引用。

>>> import pprint
>>> numbers = list(range(1,6))
>>> numbers.append(numbers)
>>> print (numbers)
[1, 2, 3, 4, 5, [...]]
>>> pprint.pprint(numbers)
[1, 2, 3, 4, 5, <Recursion on list with id=1403633698824>]

限制輸出寬度

如果將 width 引數從預設的 80 更改為其他值,則輸出將以多行顯示的方式進行格式化,同時注意不要違反語法。

import pprint
students = {"Dilip":["English", "Maths", "Science"],
"Raju":{"English":50,"Maths":60, "Science":70},
"Kalpana":(50,60,70)}
pp=pprint.PrettyPrinter(width = 20)
pp.pprint(students)

此程式碼與本文中的第一個示例類似。但是,PrettyPrinter 物件是用 width 引數為 20 構造的。因此,pprint 輸出相應地進行了格式化。

{'Dilip': [ 'English',
   'Maths',
   'Science'],
'Kalpana': (50,
   60,
   70),
'Raju': {'English': 50,
   'Maths': 60,
   'Science': 70}}

更新於:2020年6月27日

1K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.