【问题标题】:python return dictionary in separate lines in __repr__ methodpython在__repr__方法中的单独行中返回字典
【发布时间】:2014-10-06 08:44:39
【问题描述】:

我需要使用 repr 方法返回我在类中生成的字典,并且我希望它在单独的行中返回。

有什么办法可以做到吗?

def __repr__:
    return str(self.maze)

预期:

{
(0, 0):[(0, 1), (1, 0)]
(0, 1):[(0, 0), (1, 1)]
(1, 0):[(0, 0), (1, 1)]
(1, 1):[(0, 1), (1, 0)]
}

我得到了什么:

{(0, 1): [(0, 0), (1, 1)], (1, 0): [(0, 0), (1, 1)], (0, 0): [(0, 1), (1, 0)], (1, 1): [(0, 1), (1, 0)]}

由于我不能使用“pprint”,所以我不知道是否还有其他方法可以做到。

【问题讨论】:

  • 为什么不能完全使用pprint
  • 当我在 repr 中使用 pprint 时出现语法错误,并且 print 不会让我在花括号后换行
  • 我敢打赌您会遇到语法错误,因为您在没有参数的情况下输入了 def __repr__: 而不是 def __repr__(self):
  • @abarent 实际上我确实有参数是 def __repr__(self)
  • 多行代表有点粗鲁,当它们嵌入更大的结构时效果不佳。也许为这个方法使用不同的名称?

标签: python dictionary repr


【解决方案1】:

我认为你有充分的理由不能使用pprint ...但这应该没那么难:

def __repr__(self):
    inner_lines = '\n'.join('%s:%s' % (k, v) for k, v in self.maze.items())
    return """\
{
%s
}""" % inner_lines

例如:

>>> def fmt_dct(d):
...   inner_lines = '\n'.join('%s:%s' % (k, v) for k, v in d.items())
...   return """\
... {
... %s
... }""" % inner_lines
... 
>>> print fmt_dct(d)
{
(0, 1):['abcdefg']
(0, 2):['foo', 'bar']
}

【讨论】:

    【解决方案2】:

    首先,如果您认为不能使用pprint 的唯一原因是因为您没有查看the docs 并假设pprint.pprint 是模块中唯一的东西——好吧,事实并非如此,甚至如果是这样,您始终可以创建一个 StringIO 并将其作为 stream 参数传入。

    但如果您想手动操作,当然可以。您只需要考虑规则,并将它们转换为 Python。

    让我们长篇大论:

    def __repr__(self):
        lines = ['{']
        for key, value in self.maze.items():
            lines.append('{}:{}'.format(key, value))
        lines.append(['}'])
        return '\n'.join(lines)
    

    如果您知道如何编写列表推导式,您可能可以将其变成单行式;如果没有,要么去学习,要么保持 5 行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2020-02-20
      • 2016-07-05
      • 2015-12-13
      • 2018-02-25
      • 2012-11-23
      • 2022-11-27
      相关资源
      最近更新 更多