我想实现任意嵌套列表、元组、字典、整数、字符串、 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/