python - 像 python 代码一样打印嵌套对象(风格指南)

标签 python python-3.x

我想实现任意嵌套列表、元组、字典、整数、字符串、 bool 值和 None 值的字符串表示,以满足以下要求:

  • 这是有效的 python 代码
  • 它(或多或少)遵循Python风格指南(w.r.t.多行)

是否有一些Pythonic方法可以做到这一点,或者我必须自己编写该函数的代码吗?

这是一个例子:

test_obj = [['foo', 'bar'], ['foo', 'bar'], (1, 'Tupple'),
            {'key': 'value', 'fookey': None, 'barkey': True,
             'nested': ['a', 'nice', 'list']}]

应该会产生这样的结果:

[
    [
        "foo",
        "bar"
    ],
    [
        "foo",
        "bar"
    ],
    (
        1,
        "Tupple"
    ),
    {
        "fookey": None,
        "key": "value",
        "nested": [
            "a",
            "nice",
            "list"
        ],
        "barkey": True
    }
]

我尝试过 pprint.pprint(test_obj, indent=4, width=1) ,它很接近,但它将左/右括号放在一行中:

>>> pprint.pprint(test_obj, indent=4, width=1)
[   [   'foo',
        'bar'],
    [   'foo',
        'bar'],
    (   1,
        'Tupple'),
    {   'barkey': True,
        'fookey': None,
        'key': 'value',
        'nested': [   'a',
                      'nice',
                      'list']}]

我还尝试了 json.dumps(test_obj, indent=4) 这几乎是这样,但是 JSON 不知道元组是什么,并且关键字有点不同(null <-> true <-> True,...)

最佳答案

如果您想使用自定义格式进行打印,请编写递归函数,例如:

def pprint(obj,depth=0,indent='    '):
    if isinstance(obj,list):
        print('[')
        for x in obj:
            print(indent*(depth+1), end='')
            pprint(x,depth+1,indent)
        print(indent*depth+']')
    elif isinstance(obj,tuple):
        print('(')
        for x in obj:
            print(indent*(depth+1), end='')
            pprint(x,depth+1,indent)
        print(indent*depth+')')
    elif isinstance(obj,dict):
        print('{')
        for k, v in obj.items():
            print(indent*(depth+1)+repr(k)+': ', end='')
            pprint(v,depth+1,indent)
        print(indent*depth+'}')
    else:
        print(repr(obj))

关于python - 像 python 代码一样打印嵌套对象(风格指南),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50487912/

相关文章:

python - 将文本文件转换为Python字典

python - Fastapi 帖子无法识别我的参数

python - 在 Django 中,如何在不使用模板时生成 csrf token

python - 根据另一个系列索引从数据框中选择行

python - Windows 上 select.select() 的问题

python - 这种奇怪的结肠行为在做什么?

python - 为什么整数会自动转换为复数?

Python 从另一个列表中排序一个列表

python - Pandas - 如何创建从连续两行中的值派生的新列?

python - Azure 函数以最大间隔超时,而调用尚未达到最大间隔