【问题标题】:Creating a map/contents of any object创建任何对象的地图/内容
【发布时间】: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_repr decorator 用于解决自递归数据结构的问题。
  • 虽然这并不能完全解决我的问题,因为我正在处理不能简单重载的内置数据类型。然而reprlib.Repr 对象可能是一个有用的例子,例如我可以重载repr_instance 方法并且几乎得到我想要的功能。谢谢!

标签: python list recursion python-3.6


【解决方案1】:

您应该看看pprint 模块,它是标准发行版的一部分。它已经解决了这个问题,因此可以作为代码的基础。 (我可以很容易地看到,例如,通过子类化 PrettyPrinter 类来添加数字。)

这段代码:

class Aclass:
    def __init__(self):
        self.a = [12, 24]
        self.b = 5

a = [Aclass(), 1, "2", 3, 4, Aclass(), {"c":"d","e":"f"}]

import pprint
s = pprint.pformat(a, indent=4)
print(s)

产生这个输出:

[   <__main__.Aclass object at 0x1060fb160>,
    1,
    '2',
    3,
    4,
    <__main__.Aclass object at 0x1060fb198>,
    {'c': 'd', 'e': 'f'}]

【讨论】:

  • 谢谢,我得仔细看看 pprint 模块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 2017-12-10
  • 2013-12-15
  • 1970-01-01
相关资源
最近更新 更多