python counter怎么用_在Python中集合.计数器使用,Collectionscounter,用法

Counter objects

A counter tool is provided to support convenient and rapid tallies. For example:

>>> # Tally occurrences of words in a list

>>> cnt = Counter()

>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:

... cnt[word] += 1

>>> cnt

Counter({'blue': 3, 'red': 2, 'green': 1})

>>> # Find the ten most common words in Hamlet

>>> import re

>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())

>>> Counter(words).most_common(10)

[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),

('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

class

collections.

Counter

([

iterable-or-mapping

])

A

Counter

is a

dict

subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The

Counter

class is similar to bags or multisets in other languages.

计数器是一个用于计算可哈希对象的dict子类,它是一个无序的集合,其中的元素存储为字典键,它们的计数存储为字典值。它是一个无序的集合,其中元素被存储为字典键,而它们的计数被存储为字典值。计数可以是任何整数值,包括零或负数。Counter类类似于其他语言中的bag或multisets。

Elements are counted from an

iterable

or initialized from another

mapping

(or counter):元素的计数来自一个可迭代的或从另一个映射(或计数器)初始化的。

>>> c = Counter() # a new, empty counter

>>> c = Counter('gallahad') # a new counter from an iterable

>>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping

>>> c = Counter(cats=4, dogs=8) # a new counter from keyword args

Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a

KeyError

:计数器对象有一个字典接口,除了它们对丢失的项目返回一个零计数,而不是引发一个KeyError。

>>> c = Counter(['eggs', 'ham'])

>>> c['bacon'] # count of a missing element is zero

0

Setting a count to zero does not remove an element from a counter. Use

del

to remove it entirely:将计数设置为零并不会从计数器中删除一个元素。使用del可以完全删除它。

>>> c['sausage'] = 0 # counter entry with a zero count

>>> del c['sausage'] # del actually removes the entry

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值