如何强制pprint每行打印一个list / tuple / dict元素?

时间:2013-03-21 14:42:43

标签: python list dictionary pretty-print pprint

如何强制pprint()每行打印一个list / tuple / dict元素?

>>> 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'}]

1 个答案:

答案 0 :(得分:7)

对pprint()使用width = 1参数:

>>> 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