手机怎么安装py thon

Python Counter class is part of Collections module. Counter is a subclass of Dictionary and used to keep track of elements and their count.

Python Counter类是Collections模块的一部分。 Counter是Dictionary的子类,用于跟踪元素及其数量。

Python计数器 (Python Counter)

Counter is an unordered collection where elements are stored as Dict keys and their count as dict value.

计数器是一个无序集合,其中元素存储为Dict键,其计数为dict值。

Counter elements count can be positive, zero or negative integers. However there is no restriction on it’s keys and values. Although values are intended to be numbers but we can store other objects too.

计数器元素count可以为正,零或负整数。 但是,对其键和值没有限制。 尽管值旨在为数字,但我们也可以存储其他对象。

创建Python计数器对象 (Creating Python Counter Object)

We can create an empty Counter or start with some initial values too.

我们可以创建一个空的Counter或也可以从一些初始值开始。

from collections import Counter# empty Counter
counter = Counter()
print(counter)  # Counter()# Counter with initial values
counter = Counter(['a', 'a', 'b'])
print(counter)  # Counter({'a': 2, 'b': 1})counter = Counter(a=2, b=3, c=1)
print(counter)  # Counter({'b': 3, 'a': 2, 'c': 1})

We can also use any Iterable as argument for creating Counter object. So string literal and List can be used too for creating Counter object.

我们还可以使用任何Iterable作为创建Counter对象的参数。 因此字符串文字和列表也可以用于创建Counter对象。

# Iterable as argument for Counter
counter = Counter('abc')
print(counter)  # Counter({'a': 1, 'b': 1, 'c': 1})# List as argument to Counter
words_list = ['Cat', 'Dog', 'Horse', 'Dog']
counter = Counter(words_list)
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})# Dictionary as argument to Counter
word_count_dict = {'Dog': 2, 'Cat': 1, 'Horse': 1}
counter = Counter(word_count_dict)
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})

As I mentioned above, we can use non-numeric data for count values too, but that will defect the purpose of Counter class.

正如我上面提到的,我们也可以将非数字数据用于计数值,但是这会抵消Counter类的用途。

# Counter works with non-numbers too
special_counter = Counter(name='Pankaj', age=20)
print(special_counter)  # Counter({'name': 'Pankaj', 'age': 20})

Python计数器方法 (Python Counter Methods)

Let’s look into Counter class methods and some other operations we can perform on it.

让我们看一下Counter类的方法以及我们可以对其执行的其他一些操作。

获取元素数 (Getting Count of Elements)

# getting count
counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
countDog = counter['Dog']
print(countDog)  # 2

If we try to get the count of non-existing key, it will return 0 and not throw KeyError.

如果我们尝试获取不存在的键的计数,它将返回0而不抛出KeyError

# getting count for non existing key, don't cause KeyError
print(counter['Unicorn'])  # 0

设置元素数 (Setting Count of Elements)

We can also set the count of existing element in the counter. If the element doesn’t exist, then it gets added to the counter.

我们还可以设置计数器中现有元素的计数。 如果该元素不存在,则将其添加到计数器。

counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
# setting count
counter['Horse'] = 0
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})# setting count for non-existing key, adds to Counter
counter['Unicorn'] = 1
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Unicorn': 1, 'Horse': 0})

从Counter删除元素 (Deleting an element from Counter)

We can use del to delete an element from the counter object.

我们可以使用del从计数器对象中删除一个元素。

# Delete element from Counter
del counter['Unicorn']
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})

elements() (elements())

This method returns the list of elements in the counter. Only elements with positive counts are returned.

此方法返回计数器中的元素列表。 仅返回具有正计数的元素。

counter = Counter({'Dog': 2, 'Cat': -1, 'Horse': 0})# elements()
elements = counter.elements()  # doesn't return elements with count 0 or less
for value in elements:print(value)

Above code will print “Dog” two times because it’s count is 2. Other elements will be ignored because they don’t have positive count. Counter is an unordered collection, so elements are returned in no particular order.

上面的代码将两次打印“ Dog”,因为它的计数是2。其他元素将因为它们没有正计数而被忽略。 Counter是无序集合,因此元素没有特定顺序返回。

most_common(n) (most_common(n))

This method returns the most common elements from the counter. If we don’t provide value of ‘n’ then sorted dictionary is returned from most common the least common elements. We can use slicing to get the least common elements on this sorted dictionary.

此方法从计数器返回最常见的元素。 如果我们不提供'n'值,则从最常见的最不常见元素返回排序后的字典。 我们可以使用切片来获得此排序字典中最不常见的元素。

counter = Counter({'Dog': 2, 'Cat': -1, 'Horse': 0})# most_common()
most_common_element = counter.most_common(1)
print(most_common_element)  # [('Dog', 2)]least_common_element = counter.most_common()[:-2:-1]
print(least_common_element)  # [('Cat', -1)]

减去()和更新() (subtract() and update())

Counter subtract() method is used to subtract element counts from another counter. update() method is used to add counts from another counter.

计数器subtract()方法用于从另一个计数器中减去元素计数。 update()方法用于添加另一个计数器的计数。

counter = Counter('ababab')
print(counter)  # Counter({'a': 3, 'b': 3})
c = Counter('abc')
print(c)  # Counter({'a': 1, 'b': 1, 'c': 1})# subtract
counter.subtract(c)
print(counter)  # Counter({'a': 2, 'b': 2, 'c': -1})# update
counter.update(c)
print(counter)  # Counter({'a': 3, 'b': 3, 'c': 0})

Python计数器算术运算 (Python Counter Arithmetic Operations)

We can perform some arithmetic operations on Counters too, just like numbers. However only elements with positive count are returned with these operations.

我们也可以像数字一样在Counters上执行一些算术运算。 但是,这些操作仅返回具有正计数的元素。

# arithmetic operations
c1 = Counter(a=2, b=0, c=-1)
c2 = Counter(a=1, b=-1, c=2)c = c1 + c2  # return items having +ve count only
print(c)  # Counter({'a': 3, 'c': 1})c = c1 - c2  # keeps only +ve count elements
print(c)  # Counter({'a': 1, 'b': 1})c = c1 & c2  # intersection min(c1[x], c2[x])
print(c)  # Counter({'a': 1})c = c1 | c2  # union max(c1[x], c2[x])
print(c)  # Counter({'a': 2, 'c': 2})

Python计数器上的其他操作 (Miscellaneous Operations on Python Counter)

Let’s look at some code snippets for miscellaneous operations we can perform on Counter objects.

让我们看一下一些可以在Counter对象上执行的其他操作的代码段。

counter = Counter({'a': 3, 'b': 3, 'c': 0})
# miscellaneous examples
print(sum(counter.values()))  # 6print(list(counter))  # ['a', 'b', 'c']
print(set(counter))  # {'a', 'b', 'c'}
print(dict(counter))  # {'a': 3, 'b': 3, 'c': 0}
print(counter.items())  # dict_items([('a', 3), ('b', 3), ('c', 0)])# remove 0 or negative count elements
counter = Counter(a=2, b=3, c=-1, d=0)
counter = +counter
print(counter)  # Counter({'b': 3, 'a': 2})# clear all elements
counter.clear()
print(counter)  # Counter()

That’s all for Python Counter class.

这就是Python Counter类的全部内容。

GitHub Repository.GitHub Repository下载完整的示例代码。

Reference: Python Docs

参考: Python文档

翻译自: https://www.journaldev.com/20806/python-counter-python-collections-counter

手机怎么安装py thon

手机怎么安装py thon_Python计数器– Py​​thon集合计数器相关推荐

  1. 手机怎么安装py thon_Python调试器– Py​​thon pdb

    手机怎么安装py thon Python pdb module provides an interactive debugging environment for Developers to debu ...

  2. 手机怎么安装py thon_Python属性装饰器– Py​​thon @property

    手机怎么安装py thon Hello friends, today we will learn about Python property decorator. In our previous tu ...

  3. linux打包运行python文件_Linux下安装pyinstaller用于将py文件打包生成一个可执行文件...

    安装使用流程 1. 首先给系统装个easy_install, 如果装了的可以跳过这步 到pypi官方网址 https://pypi.python.org/pypi/setuptools 去downlo ...

  4. python制作安装包_如何制作python安装模块(setup.py)

    Python模块的安装方法: 1. 单文件模块:直接把文件拷贝到$python_dir/lib 2. 多文件模块,带setup.py:python setup.py install 3. egg文件, ...

  5. python web py入门-1-web.py简介和安装

    背景 记录python web.py开发入门学习的过程,主要想通过这个入门,然后继续去学习python Django框架开发课程.目前我的个人技能状态是,稍微懂点selenium webUI自动化测试 ...

  6. 从SSCHA安装解析python setup.py

    https://zhuanlan.zhihu.com/p/460233022 setup( name = "CellConstructor", #包名称version = &quo ...

  7. 华为nova4手机Termux安装Linux教程

    手机配置:华为nova4,手机 上Termux安装Linux,跑scrapy. 如果你按照我的步骤一定也可以成功在手机上搭建一个Linux系统,且手机不需要root权限. 原创不易,如果文章对你有帮助 ...

  8. LibSVM学习(六)——easy.py和grid.py的使用(转)

    我们在"LibSVM学习(一)"中,讲到libSVM有一个tools文件夹,里面包含有四个python文件,是用来对参数优选的.其中,常用到的是easy.py和grid.py两个文 ...

  9. MATLAB 中出现 Undefined variable py or function py.command 错误

    虽然当在 MATLAB 命令行中输入 py.command 就能够直接加载 Python.但有时因为使用不当也会出现错误,会在命令行出现错误提示 Undefined variable "py ...

最新文章

  1. 【iOS开发-8】UIButton类型属性简单归纳以及自定义按钮的设置
  2. python-判断语句介绍
  3. ./configure --with-package=dir指定依赖的软件包
  4. java gzip 多个文件_Java Zip多文件压缩和 GZIP压缩
  5. .NET Core CLI 的性能诊断工具介绍
  6. 怎么停止skywalking_Skywalking部署常见问题以及注意事项
  7. oj系统格式错误_论文查重会不会检查格式?【paperpp吧】
  8. 解决:com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused:
  9. 网络虚拟化基础一:linux名称空间Namespaces
  10. 计算机论文的致谢部分写什么,毕业论文致谢部分怎么写-论文致谢部分如何写在线等请问毕业论文最后一部分致谢要怎么写呀. 爱问知识人...
  11. 专访|从程序员到架构师:交流和分享最能让技术人进步
  12. android开发之AsyncTask的用法
  13. zebra(斑马)PDA扫码uniapp程序小demo
  14. 物业管理系统c语言,物业管理系统C语言程序实习.doc
  15. android usb 视频播放,如何播放/循环播放USB设备上存储的照片/视频/音乐
  16. what is a rx ring/tx ring in router?
  17. 优质的凉亭 亭子 亭台ps后期素材素材推荐,不容错过
  18. [UE4]使用UMG的用户界面,设置UMG的模块依赖性(C++)
  19. 支付宝网商贷是雪中送炭么?
  20. C++ 数据结构与算法 (十一)(排序算法)

热门文章

  1. 【原创】告别恼人的水平滚动条——滚动条宽度到底是多少?
  2. [转载] python查看的统计量_python 描述性统计_Python中的基本统计:描述性统计
  3. [转载] python——连接Oracle数据库
  4. Substance PBR Guide
  5. js中的异步[Important]
  6. Debian 9 + Windows 10 双系统安装体验
  7. android系统中如何通过程序打开某个AccessibilityService
  8. 创建SSH keys用于添加到Git服务器上
  9. asp.net GridView手写事件,包括取主键、取值、更新、选择、删除
  10. [biztalk笔记]-1.Hello World!