在Python中计算对象的最佳方法是使用
collections.Counter为此目的而创建的类。它的行为类似于Python字典,但计数时使用起来稍微容易一些。您只需传递对象列表,它就会自动为您计数。
>>> from collections import Counter>>> c = Counter(['hello', 'hello', 1])>>> print cCounter({'hello': 2, 1: 1})Counter也有一些有用的方法,例如most_common,请访问文档以了解更多信息。
Counter类也可能非常有用的一种方法是update方法。通过传递对象列表实例化Counter后,可以使用update方法执行相同的操作,它将继续计数而不会删除对象的旧计数器:
>>> from collections import Counter>>> c = Counter(['hello', 'hello', 1])>>> print cCounter({'hello': 2, 1: 1})>>> c.update(['hello'])>>> print cCounter({'hello': 3, 1: 1})


