Python 2.7 : applying str to collections. 计数器和 collections.defaultdict

标签 python python-2.7

collections.Counter 和collections.defaultdict 都是继承自dict。那么它们之间导致不相似输出(“类”和“类型”)的区别是什么?

import collections

print str(collections.Counter)
print str(collections.defaultdict)

输出:

<class 'collections.Counter'>
<type 'collections.defaultdict'>

最佳答案

恐怕你在这里的回答会归结为一些相当无聊的东西:Counter 是用 Python 编写的,而 defaultdict 是用 C 编写的。

这是 collections.py .请注意,您可以向下滚动并找到 Counter 的标准类定义:

########################################################################
###  Counter
########################################################################

class Counter(dict):
    '''Dict subclass for counting hashable items.  Sometimes called a bag
    or multiset.  Elements are stored as dictionary keys and their counts
    are stored as dictionary values.
    ...
    '''

但是,defaultdict 是从 _collections 导入的:

from _collections import deque, defaultdict

this answer 中所述,这是一个用 C 编写的内置扩展。

如果对 deque(也是 C)或用 Python 编写的 collections 中的其他类进行字符串化处理,您会发现同样的行为:

>>> from collections import deque
>>> str(deque)
"<type 'collections.deque'>"
>>> from collections import OrderedDict
>>> str(OrderedDict)
"<class 'collections.OrderedDict'>"*

关于Python 2.7 : applying str to collections. 计数器和 collections.defaultdict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35805550/

相关文章:

linux - 在 Linux 上安装 pymc 时出现错误

python - 迭代器协议(protocol)。是黑魔法吗?

python - 如何在 django rest 框架中保存嵌套关系?

python - 使用 ElementTree.parse 解析 XML 文件时出错

javascript - django/backbone.js 中的 CSRF 验证失败

python - 在 PDF 文件中查找文本位置

python - 刷新时在 python getstr() 中诅咒

python - 在 pandas 列标题上方插入一行以将标题名称保存在 csv/excel 文件的第一个单元格中

windows - 属性错误 : StringIO instance has no attribute 'encoding'

internet-explorer - 绕过 Firefox 和 IE 的 webfonts 跨域策略