【发布时间】:2017-03-31 03:56:34
【问题描述】:
在 Python 3.6 中。我想要做的是创建一个可以接受任何对象的函数,然后生成一个树状内容。
类似于一本书:
1. Object
1.1 member: integer
1.2 member: list
2.1 list: element 1
2.2 list: element 2
1.3 member: string
我的目的是使用这些数字作为技术读数的关键,该数字也可以代表比 id() 生成的更易于理解的 ID 号。因为我要处理的对象都是类型,所以我希望函数是递归的。这是我到目前为止所拥有的:
def contents(a, n = 0, lim = 5, prefix=""):
index = 1
text = ""
j = None
if n < lim:
try:
for i in a.__dict__:
text = text + "\n" + ("\t" *(n)) + prefix + str(index) + ", " + str(i) + ": " + contents(a.__dict__[i], n = n + 1, prefix=str(n)+".") + ""
index += 1
except:
try:
for i, j in a.items():
text = text + "\n" + ("\t"*(n)) + prefix + str(index) + ", " + str(i) + ": " + contents(i, n = n + 1, prefix=str(n)+".") + ""
index += 1
except:
if isinstance(a, str):
text = text + "\n" + ("\t"*(n)) + prefix + str(index) + ", " + str(a) + " "
else:
try:
for i in a:
text = text + "\n" + ("\t"*(n)) + prefix + str(index) + ", " + str(i) + contents(i, n = n + 1, prefix=str(n)+".") + " "
index += 1
except:
text = text + "\n" + ("\t"*(n)) + prefix + str(index) + ", " + str(a) + " "
else:
text = text + "limit. \n"
return text
a为对象,n为当前递归次数,lim为递归限制,前缀与显示的对象ID有关。
这是测试对象
class Aclass:
def __init__(self):
self.a = [12, 24]
self.b = 5
a = [Aclass(), 1, "2", 3, 4, Aclass(), {"c":"d","e":"f"}]
我遇到的问题与列表的奇怪递归行为有关,我已经为字符串设置了一个例外,因为字符串将注册为由可迭代对象组成的可迭代对象,如果我没有,它将无限递归设置一个限制。现在,像 [1, 2, 3, 4] 这样的简单数字列表通常会将数字列出两次,就好像它分解为一个单项列表 [1],然后报告里面的数字:1。
【问题讨论】:
-
reprlib尤其是它的@recursive_reprdecorator 用于解决自递归数据结构的问题。 -
虽然这并不能完全解决我的问题,因为我正在处理不能简单重载的内置数据类型。然而
reprlib.Repr对象可能是一个有用的例子,例如我可以重载repr_instance方法并且几乎得到我想要的功能。谢谢!
标签: python list recursion python-3.6