【发布时间】:2017-07-10 15:48:14
【问题描述】:
我知道 dicts 和 sets 没有排序,所以相等的 sets 或 dicts 可能会打印不同的内容(所有测试都使用 Python 3.6.1):
>>> for obj in {0, 8}, {8, 0}, {0:0, 8:8}, {8:8, 0:0}:
print(obj)
{0, 8}
{8, 0}
{0: 0, 8: 8}
{8: 8, 0: 0}
我刚刚意识到 pprint (“pretty-print”) 对 dicts 进行排序,而不是对集合进行排序:
>>> for obj in {0, 8}, {8, 0}, {0:0, 8:8}, {8:8, 0:0}:
pprint.pprint(obj)
{0, 8}
{8, 0}
{0: 0, 8: 8}
{0: 0, 8: 8}
它的文档还说“字典在计算显示之前按键排序”。但是为什么它也不排序集合呢?在我看来并不漂亮。有没有办法制作排序集?也在嵌套结构中,因为这是 pprint 的主要目的。
【问题讨论】:
-
我猜它不支持集合,但你可以继承
pprint.PrettyPrinter并覆盖pformat来处理集合...
标签: python python-3.x dictionary set pprint