Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python返回字典在_repr____方法中以单独的行显示_Python_Dictionary_Repr - Fatal编程技术网

python返回字典在_repr____方法中以单独的行显示

python返回字典在_repr____方法中以单独的行显示,python,dictionary,repr,Python,Dictionary,Repr,我需要返回在类中使用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)],

我需要返回在类中使用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
。。。但这并不难:

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


我想你有一个很好的理由不能使用
pprint
。。。但这并不难:

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


首先,如果您认为不能使用
pprint
的唯一原因是因为您没有查看并假设
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行。

首先,如果您认为不能使用
pprint
的唯一原因是因为您没有查看并假设
pprint。pprint
是模块中唯一的内容,那么它不是,即使是,您始终可以创建一个
StringIO
,并将其作为
参数传入

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

让我们把它写下来:

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

如果你知道如何写列表理解,你可能会把它变成一行;如果没有,要么去学习,要么保持5行。

为什么你不能准确地使用
pprint
呢?当我在repr中使用pprint时,它会给我一个语法错误,而且print也不会让我在花括号后更改行。我敢打赌你会得到一个语法错误,因为你在没有参数的情况下错误了
def\urepr:
,与
def\uuu repr\uuuuuuuuuuuself(self)不同的是:
@abarent实际上我有
def\uuuu repr\uuuuuuuself(self)
多行repr有点粗鲁,当它们嵌入到更大的结构中时,效果不好。也许这个方法使用不同的名称?为什么不能准确地使用
pprint
呢?当我在repr中使用pprint时,它会给我一个语法错误,而且print也不允许我在花括号后换行。我敢打赌,你会得到一个语法错误,因为你错了
def\urepr:
没有参数,而不是
def\urepr__(self):
@abarent事实上,我确实有一些参数是
def\uuu repr\uuuuu(self)
多行repr有点粗鲁,当它们嵌入到更大的结构中时,效果不好。也许可以为这个方法使用不同的名称?