Python中的计数器|集1(初始化和更新)

柜台 是一个 容器 包括在 收藏 单元现在你们一定想知道什么是容器。先别担心,我们来讨论一下集装箱。

null

什么是集装箱?

容器是保存对象的对象。它们提供了一种访问包含的对象并对其进行迭代的方法。内置容器的例子有元组、列表和字典。其他则包括在 收藏 单元 计数器是dict的一个子类。因此,它是一个无序的集合,元素及其各自的计数存储为字典。这相当于其他语言的一个包或多个集。 语法:

class collections.Counter([iterable-or-mapping])

初始化: 计数器的构造函数可以通过以下任一方式调用:

  • 按项目顺序排列
  • 包含键和计数的字典
  • 使用关键字参数将字符串名称映射到计数

每种初始化类型的示例:

Python3

# A Python program to show different ways to create
# Counter
from collections import Counter
# With sequence of items
print (Counter([ 'B' , 'B' , 'A' , 'B' , 'C' , 'A' , 'B' , 'B' , 'A' , 'C' ]))
# with dictionary
print (Counter({ 'A' : 3 , 'B' : 5 , 'C' : 2 }))
# with keyword arguments
print (Counter(A = 3 , B = 5 , C = 2 ))


三条线路的输出相同:

Counter({'B': 5, 'A': 3, 'C': 2})Counter({'B': 5, 'A': 3, 'C': 2})Counter({'B': 5, 'A': 3, 'C': 2})

更新: 我们还可以通过以下方式创建空计数器:

coun = collections.Counter()

并且可以通过update()方法进行更新。相同的语法:

coun.update(Data)

Python3

# A Python program to demonstrate update()
from collections import Counter
coun = Counter()
coun.update([ 1 , 2 , 3 , 1 , 2 , 1 , 1 , 2 ])
print (coun)
coun.update([ 1 , 2 , 4 ])
print (coun)


输出:

Counter({1: 4, 2: 3, 3: 1})Counter({1: 5, 2: 4, 3: 1, 4: 1})

  • 数据可以通过初始化中提到的三种方式中的任何一种提供,计数器的数据将增加而不是替换。
  • 计数可以为零,也可以为负。

Python3

# Python program to demonstrate that counts in
# Counter can be 0 and negative
from collections import Counter
c1 = Counter(A = 4 ,  B = 3 , C = 10 )
c2 = Counter(A = 10 , B = 3 , C = 4 )
c1.subtract(c2)
print (c1)


  • 输出:
 Counter({'c': 6, 'B': 0, 'A': -6})
  • 我们可以使用计数器来计算列表或其他集合中的不同元素。

Python3

# An example program where different list items are
# counted using counter
from collections import Counter
# Create a list
z = [ 'blue' , 'red' , 'blue' , 'yellow' , 'blue' , 'red' ]
# Count distinct elements and print Counter aobject
print (Counter(z))


  • 输出:
Counter({'blue': 3, 'red': 2, 'yellow': 1})

本文由 马扬克·拉瓦特 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享