2013-03-21 127 views
3

如何強制pprint()每行打印一個list/tuple/dict元素?如何強制pprint打印每行一個列表/元組/元素元素?

>>> from pprint import pprint 
>>> my_var = ['one', 'two', ('red','green'), {'state' : 'Oregon', 'city' : 'Portland'}] 
>>> pprint(my_var) 
['one', 'two', ('red', 'green'), {'city': 'Portland', 'state': 'Oregon'}] 

我想輸出是這樣的:

['one', 
'two', 
('red', 
    'green'), 
{'city': 'Portland', 
    'state': 'Oregon'}] 

回答

6

使用寬度= 1參數pprint():

>>> from pprint import pprint 
>>> my_var = ['one', 'two', ('red','green'), {'state' : 'Oregon', 'city' : 'Portland'}] 
>>> pprint(my_var, width=1) 
['one', 
'two', 
('red', 
    'green'), 
{'city': 'Portland', 
    'state': 'Oregon'}] 
>>> 

"pprint - Data pretty printer" documentation

+0

這非常適用於相對平坦的對象,但對於深度嵌套的對象,每行不能工作,而我想在每次打開之後實現換行支撐。例如,嘗試'pprint'ing'{u'a':{u'b':{u'c':{u'd':{u'foo':1,u'bar':2}}} }}'。 – 2017-07-24 22:05:44