gpt4 book ai didi

python - 如何在 Python 中使用 pprint 进行缩进?

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:59 24 4
gpt4 key购买 nike

我正在尝试缩进 pprint 的输出,以便在 pprint 中缩进 8 个空格。我使用的代码是:

import numpy as np
from pprint import pprint
A = np.array([1, 2, 3, 4])
f = open("log.txt", 'w')
n = 2
for i in range(n):
A = A + 1
f.writelines(list(u' \u27B3 - %s\n'.encode('utf-8') % i for i in A))
pprint(globals())

输出

{'A': array([2, 3, 4, 5]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 0,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
{'A': array([3, 4, 5, 6]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 1,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}

期望的输出

        {'A': array([2, 3, 4, 5]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 0,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
{'A': array([3, 4, 5, 6]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 1,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}

简而言之,我在写入文件或使用pprint 打印时需要空格缩进。我试过了

pp = pprint.PrettyPrinter(indent=8)

但是没用

最佳答案

你不能让 pprint() 添加额外的前导缩进,不。

您最好的选择是使用 pprint.pformat() function相反,然后手动添加缩进:

from pprint import pformat

print ''.join([
' ' + l
for l in pformat(globals()).splitlines(True)])

这使用了 str.splitlines() methodpformat() 输出拆分为单独的行,以便于重新加入。

在 Python 3 中,缩进可以用 textwrap.indent() 完成:

from pprint import pformat
from textwrap import indent

print(indent(pformat(globals()),
' '))

关于python - 如何在 Python 中使用 pprint 进行缩进?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28937664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com