集合的计数器是否将数据排序?
我正在阅读Python Collections的 counter 。它说以下说明:
>>> from collections import Counter
>>> Counter({'z': 9,'a':4, 'c':2, 'b':8, 'y':2, 'v':2})
Counter({'z': 9, 'b': 8, 'a': 4, 'c': 2, 'y': 2, 'v': 2})
这些印刷值以降序(9> 8> 4> 2)以某种方式打印。为什么是这样? 计数器
存储值排序吗?
PS:AM上的Python 3.7.7
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就
counter
对象中存储的数据而言:从Python 3.7开始插入数据,因为Counter
是内置dict的子类
。在Python 3.7之前,没有保证数据的顺序。但是,您看到的行为来自
counter .__ repl __
。我们可以从 noreferrer“代码> 方法,该方法按值按降顺序按价值对。如果由于值不可分类而失败,则它将落回dict
表示形式,同样,该表示将插入。In terms of the data stored in a
Counter
object: The data is insertion-ordered as of Python 3.7, becauseCounter
is a subclass of the built-indict
. Prior to Python 3.7, there was no guaranteed order of the data.However, the behavior you are seeing is coming from
Counter.__repr__
. We can see from the source code that it will first try to display using theCounter.most_common
method, which sorts by value in descending order. If that fails because the values are not sortable, it will fall back to thedict
representation, which, again, is insertion-ordered.顺序取决于python版本。
python< 3.7,没有保证的订单,因为Python 3.7订单是插入的订单。
Python 3.8(3.8.10 [GCC 9.4.0])上的示例:
输出:
如何检查该
Counter
在
Counter中不计数为
返回__ str __ __
不按数量进行排序。most_common
,它不是检查订单的可靠方法。转换为
dict
,__ str __
表示表示是忠实的。The order depends on the python version.
For python < 3.7, there is no guaranteed order, since python 3.7 the order is that of insertion.
Example on python 3.8 (3.8.10 [GCC 9.4.0]):
Output:
how to check that
Counter
doesn't sort by countAs
__str__
inCounter
return themost_common
, it is not a reliable way to check the order.Convert to
dict
, the__str__
representation will be faithful.