2017-06-04 31 views
3

我有一個嵌套的字典結構與元組鍵。這裏有一個條目是什麼樣子時,我非常-打印使用pprint詞典:pprint與自定義浮動格式

... 
('A', 'B'): {'C': 0.14285714285714285, 
       'D': 0.14285714285714285, 
       'E': 0.14285714285714285, 
       'F': 0.14285714285714285, 
       'G': 0.14285714285714285, 
       'H': 0.14285714285714285, 
       'I': 0.14285714285714285}, 
... 

這是非常漂亮的,但我想從彩車削減一些額外的數字進一步自定義它。我在想,通過子類化pprint.PrettyPrint可以實現,但我不知道如何做到這一點。

謝謝。

回答

2

正如您所說,您可以通過繼承PrettyPrinter並覆蓋format方法來實現此目的。請注意,輸出不僅是格式化的字符串,還有一些標誌。

一旦你怎麼做,你也可以這樣概括,並通過一個字典,針對不同類型所需的格式轉換成構造:

class FormatPrinter(pprint.PrettyPrinter): 

    def __init__(self, formats): 
     super(FormatPrinter, self).__init__() 
     self.formats = formats 

    def format(self, obj, ctx, maxlvl, lvl): 
     if type(obj) in self.formats: 
      return self.formats[type(obj)] % obj, 1, 0 
     return pprint.PrettyPrinter.format(self, obj, ctx, maxlvl, lvl) 

例子:

>>> d = {('A', 'B'): {'C': 0.14285714285714285, 
...     'D': 0.14285714285714285, 
...     'E': 0.14285714285714285}, 
...  'C': 255} 
... 
>>> FormatPrinter({float: "%.2f", int: "%06X"}).pprint(d) 
{'C': 0000FF, 
('A', 'B'): {'C': 0.14, 
       'D': 0.14, 
       'E': 0.14}} 
+1

怎麼樣'超(FormatPrinter,self)'而不是'pprint.PrettyPrinter'? –

+2

您可能想要使用通用格式功能。所以'FormatPrinter({float:'{0:.2f}'。format})',並讓它返回self.formats [type(obj)](obj)'。 – Artyer

+0

@Artyer是的,這也是一種可能性。可能比傳遞格式字符串更通用,但也更加冗長。 –