【问题标题】:Using "Counter" in Python 3.2在 Python 3.2 中使用“计数器”
【发布时间】:2011-06-19 04:27:53
【问题描述】:

我一直在尝试在 Python 3.2 中使用 Counter 方法,但我不确定我是否正确使用它。知道为什么我会收到错误消息吗?

>>> import collections
>>> Counter()
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    Counter()
NameError: name 'Counter' is not defined

如果我访问 collections.Counter(),我可以访问 Counter,但不能访问文档中的示例。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    你想要from collections import Counter。使用import collections 只会使集合中的内容可作为集合使用。something。更多关于模块和import 的工作原理在this tutorial chapter 的前几节中。

    【讨论】:

      【解决方案2】:

      使用 Counter 试试它的工作原理

      import collections
      print collections.Counter(['a','b','c','a','b','b'])
      

      输出:

      Counter({'b': 3, 'a': 2, 'c': 1})
      

      【讨论】:

      • 它看起来不像 python 3.2 它看起来像 2.7 或 2.x
      • 标题是“在 Python 3.2 中使用计数器”。这对接受的答案有什么好处?请阅读How do I write a good answer?
      猜你喜欢
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      相关资源
      最近更新 更多