【问题标题】:create a python object/instance of format with equal signs创建一个带有等号的python对象/格式实例
【发布时间】:2020-09-06 12:53:39
【问题描述】:

我想在打印时在 python 中创建以下格式的结构。基本上是一本字典,但用等号而不是冒号。我找不到它的确切类型,但应该是可能的

打印 obj1

obj1 = {a = {aa = 1, ab = 2}, b = {ba = 3, bb = 5}, c = [1 2 4]}

【问题讨论】:

  • 如果你想打印字典的非标准字符串表示,听起来你应该只使用字典并编写自定义格式化函数。

标签: python object types instance


【解决方案1】:

这是无效的语法。在 python 中,您不能创建带有等号的dict

【讨论】:

    【解决方案2】:

    您可以像这样创建一个类,其__str__ 方法将格式化字典的输出:

    class DictionaryFormatter():
        def __init__(self, dictionary):
            self.obj1 = dictionary
    
        def __str__(self):
            obj1_str = str(self.obj1)
            obj1_str = obj1_str.replace("'", "")
            obj1_str = obj1_str.replace(":", " =")
            return f"obj1 = {obj1_str}"
    
    d = {
        "a": {"aa": 1, "ab": 2},
        "b": {"ba": 3, "bb": 5},
        "c": [1, 2, 4]
    }
    
    print(DictionaryFormatter(d))
    print("obj1 = {a = {aa = 1, ab = 2}, b = {ba = 3, bb = 5}, c = [1 2 4]}")
    

    输出:

    obj1 = {a = {aa = 1, ab = 2}, b = {ba = 3, bb = 5}, c = [1, 2, 4]}
    obj1 = {a = {aa = 1, ab = 2}, b = {ba = 3, bb = 5}, c = [1 2 4]}
    

    如您所见,输出并不完美,因为c 使用逗号,但这应该很容易修复。我希望你明白这个想法,这就是你要找的。​​p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-10
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 2020-04-18
      • 2019-03-26
      相关资源
      最近更新 更多