python - Print nested object like python code (style guide)
问题描述
I'd like to achieve a string representation of arbitrarily nested lists, tuples, dicts, ints, strings, bools, and None values that fulfills the following requirements:
- It's valid python code
- It follows (more or less) the python style guide (w.r.t. multiple lines)
Is there some pythonic way to do it or do I have to code that function my own?
Here is an example:
test_obj = [['foo', 'bar'], ['foo', 'bar'], (1, 'Tupple'),
{'key': 'value', 'fookey': None, 'barkey': True,
'nested': ['a', 'nice', 'list']}]
Should result in something like this:
[
[
"foo",
"bar"
],
[
"foo",
"bar"
],
(
1,
"Tupple"
),
{
"fookey": None,
"key": "value",
"nested": [
"a",
"nice",
"list"
],
"barkey": True
}
]
I've tried pprint.pprint(test_obj, indent=4, width=1)
which is close but it puts opening/closing brackets in one line:
>>> pprint.pprint(test_obj, indent=4, width=1)
[ [ 'foo',
'bar'],
[ 'foo',
'bar'],
( 1,
'Tupple'),
{ 'barkey': True,
'fookey': None,
'key': 'value',
'nested': [ 'a',
'nice',
'list']}]
I also tried json.dumps(test_obj, indent=4)
which is pretty much it but JSON does not know what tuples are and the keywords are a little different (null
<-> None
, true
<-> True
, …)
解决方案
If you want to print with your custom format, write a recursive function, e.g.:
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))
推荐阅读
- java - 使用正则表达式删除字符串中的前导大写字符
- javascript - [i] 在这个函数中做了什么?
- kubernetes - 如果我更新一个秘密,它是否会自动更新到它被卷安装的所有资源?
- mysql - 将每个日期的月份名称统一起来
- node.js - 为什么 NodeJs 中的任何函数都可以有 req、res 和 next 作为参数?
- java - Jackson 序列化 - 动态更改元素名称
- html - 如何在角度的每个块中以相同的方式设置div的高度和宽度
- vb.net - 如何动态将标签页添加到标签控件并将标签添加到标签页
- sockets - Windows 10 iot 核心 (rpi3) 上的套接字通信
- javascript - Html 有没有办法将 concat 从桌面发送到手机?