有什么方法可以正确地预先打印订单吗?

2024-09-29 19:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我喜欢Python中的pprint模块。我经常使用它进行测试和调试。我经常使用width选项来确保输出很好地符合我的终端窗口

直到他们在Python2.7中添加了新的ordered dictionary type(我非常喜欢的另一个很酷的特性)之前,它一直工作得很好。如果我试图漂亮地打印一个有序的字典,它不会很好地显示出来。与其将每个键值对放在自己的行上,不如将整个内容显示在一条长的行上,这条长的行包含了很多次,而且很难阅读:

>>> from collections import OrderedDict
>>> o = OrderedDict([("aaaaa", 1), ("bbbbbb", 2), ("ccccccc", 3), ("dddddd", 4), ("eeeeee", 5), ("ffffff", 6), ("ggggggg", 7)])
>>> import pprint
>>> pprint.pprint(o)
OrderedDict([('aaaaa', 1), ('bbbbbb', 2), ('ccccccc', 3), ('dddddd', 4), ('eeeeee', 5), ('ffffff', 6), ('ggggggg', 7)])

这里有没有人有办法让它像旧的无序字典一样漂亮地打印出来?如果我花足够的时间,我可能会想出一些办法,可能是使用PrettyPrinter.format方法,但我想知道这里是否有人已经知道了解决方案

更新:我为此提交了一份错误报告。你可以在http://bugs.python.org/issue10592看到它


Tags: 模块import字典widthordereddictpprint行上办法
3条回答

如果OrderedDict的顺序为alpha排序,则以下操作将起作用,因为pprint将在打印前对dict进行排序

>>> from collections import OrderedDict
>>> o = OrderedDict([("aaaaa", 1), ("bbbbbb", 2), ("ccccccc", 3), ("dddddd", 4), ("eeeeee", 5), ("ffffff", 6), ("ggggggg", 7)])
>>> import pprint
>>> pprint.pprint(dict(o.items()))
{'aaaaa': 1,
 'bbbbbb': 2,
 'ccccccc': 3,
 'dddddd': 4,
 'eeeeee': 5,
 'ffffff': 6,
 'ggggggg': 7}

自Python 3.7以来,Python保证字典中的键将保持其插入顺序。因此,如果您使用的是Python3.7+,则无需确保OrderedDict按字母顺序排序

自Python 3.7以来,Python保证字典中的键将保持其插入顺序。(尽管它们的行为与OrderedDict对象并不完全相同,因为两个dict ab可以被视为相等a == b,即使键的顺序不同,而OrderedDict在测试相等性时会检查这一点。)

Python 3.8或更新版本:

您可以使用sort_dicts=False来阻止它按字母顺序对它们进行排序:

>>> example_dict = {'x': 1, 'b': 2, 'm': 3}
>>> import pprint
>>> pprint.pprint(example_dict, sort_dicts=False)
{'x': 1, 'b': 2, 'm': 3}

Python 3.7或更早版本:

作为临时解决方法,您可以尝试以JSON格式转储,而不是使用pprint

您丢失了一些类型信息,但它看起来不错,并且保持了顺序

>>> import json
>>> print(json.dumps(example_dict, indent=4))
{
    "x": 1,
    "b": 2,
    "m": 3
}

下面是另一个答案,它通过在内部重写和使用stockpprint()函数来工作。与我的earlier one不同,它处理另一个容器(如list)中的OrderedDict,并且还应该能够处理给定的任何可选关键字参数-但是它对输出的控制程度与另一个容器不同

它将stock函数的输出重定向到一个临时缓冲区,然后word在将其发送到输出流之前对其进行包装。虽然最终产出的产品也不例外地漂亮,但它很不错,可能“足够好”可以作为一种变通方法

更新2.0

通过使用标准库textwrap模块进行简化,并修改为在 Python2和;3.

from collections import OrderedDict
try:
    from cStringIO import StringIO
except ImportError:  # Python 3
    from io import StringIO
from pprint import pprint as pp_pprint
import sys
import textwrap

def pprint(object, **kwrds):
    try:
        width = kwrds['width']
    except KeyError: # unlimited, use stock function
        pp_pprint(object, **kwrds)
        return
    buffer = StringIO()
    stream = kwrds.get('stream', sys.stdout)
    kwrds.update({'stream': buffer})
    pp_pprint(object, **kwrds)
    words = buffer.getvalue().split()
    buffer.close()

    # word wrap output onto multiple lines <= width characters
    try:
        print >> stream, textwrap.fill(' '.join(words), width=width)
    except TypeError:  # Python 3
        print(textwrap.fill(' '.join(words), width=width), file=stream)

d = dict((('john',1), ('paul',2), ('mary',3)))
od = OrderedDict((('john',1), ('paul',2), ('mary',3)))
lod = [OrderedDict((('john',1), ('paul',2), ('mary',3))),
       OrderedDict((('moe',1), ('curly',2), ('larry',3))),
       OrderedDict((('weapons',1), ('mass',2), ('destruction',3)))]

样本输出:

pprint(d, width=40)

»{'john': 1, 'mary': 3, 'paul': 2}

pprint(od, width=40)

»OrderedDict([('john', 1), ('paul', 2),
('mary', 3)])

pprint(lod, width=40)

»[OrderedDict([('john', 1), ('paul', 2),
('mary', 3)]), OrderedDict([('moe', 1),
('curly', 2), ('larry', 3)]),
OrderedDict([('weapons', 1), ('mass',
2), ('destruction', 3)])]

相关问题 更多 >

    热门问题