pprint排序字典,但没有设置? [英] pprint sorting dicts but not sets?

查看:239
本文介绍了pprint排序字典,但没有设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道字典和集合没有顺序,因此相等的集合或字典可能会以不同的方式显示(所有使用Python 3.6.1的测试):

I know that dicts and sets aren't ordered, so equal sets or dicts may print differently (all tests with 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 (漂亮的打印" )对字典进行排序,但不进行设置:

And I just realized that pprint ("pretty-print") sorts dicts but not sets:

>>> 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的主要目的.

It's documentation also says "Dictionaries are sorted by key before the display is computed". But why doesn't it also sort sets? Doesn't seem pretty to me. And is there a way to make it sort sets? Also inside nested structures, as that's a main purpose of pprint.

推荐答案

此问题出现在问题中27495 ,这是一个错误,而不仅仅是设计选择,但显然尚未解决.

This was raised in issue 27495 and it is a bug, rather than just a design choice, but apparently has not yet been resolved.

这里是该问题的另一个示例,它可能更清楚地说明了您在Python 3中识别出的行为:

Here is another example from the issue that illustrates perhaps more obviously the behavior you identify in Python 3:

>>> import string, pprint
>>> pprint.pprint(set(string.digits))
{'7', '1', '9', '8', '3', '0', '2', '5', '6', '4'}

frozenset()同样适用,但是请注意,多行pprint输出 在Python 3中进行了排序,例如:

The same applies for frozenset() too, but note that multi-line pprint outputs are sorted in Python 3, for example:

>>> pprint.pprint(set(string.digits), width=1)
{'0',
 '1',
 '2',
 '3',
 '4',
 '5',
 '6',
 '7',
 '8',
 '9'}

但是,在Python 2中,对相同原始代码的输出进行了排序:

However, in Python 2, the output from the same original code is sorted:

>>> pprint.pprint(set(string.digits))
set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])

我认为是Python 3和Python 2之间以及单行多行行为之间的不一致,这使它成为一个错误.

I think it is the inconsistency between Python 3 and Python 2, and between the single-line multi-line behavior, that makes this a bug.

对于一个dict,类似的示例,正​​如您所注意到的,说明了输出是以Python 3或2进行排序的,应该是这样:

For dicts, a similar example, illustrates as you note, that the output is sorted in either Python 3 or 2, as it should be:

>>> pprint.pprint({i:None for i in set(string.digits)})
{'0': None,
 '1': None,
 '2': None,
 '3': None,
 '4': None,
 '5': None,
 '6': None,
 '7': None,
 '8': None,
 '9': None}

但是,对于Python 3.6,pprintdict进行排序可能令人感到惊讶,因为它们

However, for Python 3.6, it could be considered surprising that pprint sorts dicts since they are ordered now. However, since this is just an implementation detail (for now) I guess there is no obligation for pprint to maintain the insertion order (yet), and doing so would break pprint's own consistency across Python versions of always sorting dicts.

这篇关于pprint排序字典,但没有设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆