标准类库-数据类型之集合-容器数据类型

 

by:授客 QQ:1033553122

Counter对象

例子

>>> from collections import Counter

>>> cnt = Counter()

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

cnt[word]  += 1  # 等同 cnt[word] = cnt[word] + 1

cnt[word] 每个list元素出现的次数,但是这里相加时会自动去掉重复统计

>>> cnt

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

test.txt内容如下

the and  to of you a my hamlet in

the and  to of you a my hamlet in

the and  to of you a my hamlet in

the to of you a my hamlet in

the of you a my hamlet in

the  you a my hamlet in

the  a my hamlet in

the  my hamlet in

the  hamlet in

the  in

in

good by 2016

shouke 2017

1099

study python Counter

>>> import re

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

>>> print(words)

['the', 'and', 'to', 'of', 'you', 'a', 'my', 'hamlet', 'in', 'the', 'and', 'to', 'of', 'you', 'a', 'my', 'hamlet', 'in', 'the', 'and', 'to', 'of', 'you', 'a', 'my', 'hamlet', 'in', 'the', 'to', 'of', 'you', 'a', 'my', 'hamlet', 'in', 'the', 'of', 'you', 'a', 'my', 'hamlet', 'in', 'the', 'you', 'a', 'my', 'hamlet', 'in', 'the', 'a', 'my', 'hamlet', 'in', 'the', 'my', 'hamlet', 'in', 'the', 'hamlet', 'in', 'the', 'in', 'in', 'good', 'by', '2016', 'shouke', '2017', '1099', 'study', 'python', 'counter']

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

[('in', 11), ('the', 10), ('hamlet', 9), ('my', 8), ('a', 7), ('you', 6), ('of', 5), ('to', 4), ('and', 3), ('2016', 1)]

说明:\w 只匹配字母和数字字符

类说明

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

Counter,用于统计哈希对象的dict子类,是一个无序集合,把被统计元素存储为字典的键,而把对应元素出现的次数存储为字典的值。

可统计可迭代对象(iterable)、其它mapping对象、counter中的元素

>>> c = Counter() # 空的 counter

>>> c

Counter()

>>> c = Counter('gallahad')  # 通过可迭代对象(字符串)创建的counter

>>> c

Counter({'a': 3, 'l': 2, 'd': 1, 'h': 1, 'g': 1})

>>> c = Counter([2, 3, 4, 3, 3, 4]) # 通过可迭代对象(List)创建的counter

>>> c

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

>>> c = Counter({'red':4, 'blue':2}) # 通过mapping对象(字典)创建的counter

>>> c

Counter({'red': 4, 'blue': 2})

>>> c = Counter(cats=4, dogs=8) # 通过关键字参数创建的counter

>>> c

Counter({'dogs': 8, 'cats': 4})

Counter对象拥有字典的接口,可通过字典方式,如counter[element]获取element的统计次数,如果key即element不存在,则返回0

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

>>> c

Counter({'ham': 1, 'eegs': 1})

>>> c['bacon']

0

修改某个元素的统计次数,然后使用del移除该元素的统计

>>> c = Counter(['shouke', 'shouke', '2017'])

>>> c

Counter({'shouke': 2, '2017': 1})

>>> c['shouke'] = 1

>>> c

Counter({'shouke': 1, '2017': 1})

>>> del c['shouke']

>>> c

Counter({'2017': 1})

3.1中新增

对象方法

除了支持字典对象所拥的方法之外,Counter对象还支持以下三种方法

elements()

返回一个List,如果存在被统计元素,且元素统计次数大于0,假设为N,则该元素会在list中重复出现N次。List中元素未知顺序任意。

>>> c = Counter(a=4, b=2, c=0, d=-2)

>>> c.elements()

>>> list(c.elements())

['b', 'b', 'a', 'a', 'a', 'a']

注意:统计次数小于0的元素被忽略了。

 

most_common([n])

返回元素统计次数排名前N位的元素,如果不指定N,默认返回全部元素的统计。如果元素彼此的统计次数相等,则元素的顺序任意。

>>> Counter('abracadabra').most_common(3)

[('a', 5), ('b', 2), ('r', 2)]

subtract([iterable-or-mapping])

counter相减(对应元素的统计次数相减)

>>> c = Counter(a=4, b=2, c=0, d=-2)

>>> d = Counter(a=1, b=2, c=3, d=4)

>>> c.subtract(d)

>>> c

Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

>>> d = Counter(a=1, b=2, c=3, d=4, e=2)

>>> c.subtract(d)

>>> c

Counter({'a': 2, 'b': -2, 'e': -2, 'c': -6, 'd': -10})

说明:如上,如果后一个counter中的元素在前一个counter中未出现,则默认前一个counter中该元素的统计次数为0

3.2中新增

以下两个常规的字典方法,对于Counter对象,有点不一样

fromkeys(iterable)

该方法对于counter对象来说,未实现。

 

update([iterable-or-mapping])

根据提供的可迭代对象,或者映射对象,或者counter更新统计次数。可迭代对象,期望是元素序列,而(key,value)非键值对序列

>>> c = Counter(a=4, b=2, c=0, d=-2)

>>> c.update(['d', 'd', 'a', 'c', 'e'])

>>> c

Counter({'a': 5, 'b': 2, 'c': 1, 'e': 1, 'd': 0})

Counter对象常见使用模式

>>> c

Counter({'a': 5, 'b': 2, 'c': 1, 'e': 1, 'd': 0})

>>> sum(c.values())  # 获取元素统计次数之和

9

>>> c.clear() # 清空统计

>>> c

Counter()

>>> c = Counter(['shou', 'ke', '2014', '2017', '2017'])

>>> c

Counter({'2017': 2, '2014': 1, 'ke': 1, 'shou': 1})

>>> list(c)  # 返回元素的list表示,元素唯一,不改变Counter对象

['2017', '2014', 'ke', 'shou']

>>> set(c)  # 返回元素的set集合,不改变Counter对象

{'2017', '2014', 'ke', 'shou'}

>>> dict(c)  # 返回包含elem:cnt(元素:统计次数)对的字典,不改变Counter对象

{'2017': 2, '2014': 1, 'ke': 1, 'shou': 1}

>>> c.items() # 所有统计项

dict_items([('2017', 2), ('2014', 1), ('ke', 1), ('shou', 1)])

# Counter(dict([(elem,cnt),(elem,cnt)])) # 从包含(elem,cnt)对的list创建counter对象

>>> Counter(dict([('shou',2),('ke',1)]))

Counter({'shou': 2, 'ke': 1})

# c.most_common()[:-n:-1],返回统计次数最少的前 n-1项

>>> c.most_common()[:-3:-1]

[('shou', 1), ('ke', 1)]

>>> c = Counter(dict([('shou', 1), ('ke',2), ('2014', 0),('2017',-1)]))

>>> +c  # 返回移除了统计值为0、负数的统计项后的Counter

Counter({'ke': 2, 'shou': 1})

>>> c

Counter({'ke': 2, 'shou': 1, '2014': 0, '2017': -1})

>>>

数学运行

输出只会保留统计大于0的统计项

>>> c = Counter(a=3, b=1)

>>> d = Counter(a=1, b=2)

>>> c + d  # c[x] + d[x]

Counter({'a': 4, 'b': 3})

>>> c -d   #  c[x] - d[x]

Counter({'a': 2})  #忽略了统计值为0的项

>>> c & d  # min(c[x], d[x])

Counter({'b': 1, 'a': 1})

>>> c | d  # max(c[x], d[x])

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

添加空的Counter、用空的counter减去当前Counter的简写方法

>>> c = Counter(a=2, b=-4)

>>> +c

Counter({'a': 2})

>>> -c

Counter({'b': 4})

>>>

3.3新增

New in version 3.3: Added support for unary plus, unary minus, and in-place multiset operations

应用举例

类似如下的一个列表,数据总量达100w,要提取其中重复的数据。

解决方案:逐行读取,把读取的数据保存在list中,然后如下,构造Counter对象,然后判断Counter对象中,元素统计值是否大于1,大于1则表明存在重复数据,print,(实践测试,实际处理耗时: 1s)

# 获取重复数据
c
= Counter(list_data)
for

item
in

c.items():
    if

item[1]
>
1:
        print('重复数据:%s'

% item[0])

查看更多类型介绍,烦参考官方文档

python 标准类库-数据类型之集合-容器数据类型的更多相关文章

  1. Python 标准类库-数据类型之copy-深拷贝浅拷贝操作

    标准类库-数据类型之copy-深拷贝浅拷贝操作   by:授客 QQ:1033553122 Python中赋值并不会拷贝对象,只是创建目标和对象的绑定关系. copy.copy(x) 返回x的浅拷贝 ...

  2. python 标准类库-并行执行之subprocess-子进程管理

    标准类库-并行执行之subprocess-子进程管理 by:授客QQ:1033553122 1.使用subprocess模块 以下函数是调用子进程的推荐方法,所有使用场景它们都能处理.也可用Popen ...

  3. Python 标准类库- 因特网协议于支持之UUID

    标准类库- 因特网协议于支持之UUID by:授客 QQ:1033553122   测试环境 python3 UUID生成函数定义 uuid.getnode() 获取一个表示硬件地址的48位正整数.第 ...

  4. Python 标准类库 - 因特网协议与支持之socketserver

    标准类库 - 因特网协议与支持之socketserver by:授客 QQ:1033553122 socketserver 模块,简化网络服务编写任务. 创建服务的步骤 1  通过子类化BaseReq ...

  5. Python 标准类库-Windows特殊服务之msvcrt

    标准类库-Windows特殊服务之msvcrt   by:授客 QQ:1033553122 广告:出售自研自动化小平台(无需编码也可用),有需要请联系 测试环境 win7 64位 Python 3.4 ...

  6. Python 标准类库-日期类型之datetime模块

    标准类库-日期类型之datetime模块    by:授客 QQ:1033553122 可用类型 3 实践出真知 4 timedelta对象 4 class datetime.timedelta(da ...

  7. Python 标准类库-数字和数学模块之decimal使用简介

    标准类库-数字和数学模块之decimal使用简介 by:授客 QQ:1033553122 例子 >>>from decimal import * >>>getcon ...

  8. Python3标准库:collections容器数据类型

    1. collections容器数据类型 collections模块包含除内置类型list.dict和tuple以外的其他容器数据类型. 1.1 ChainMap搜索多个字典 ChainMap类管理一 ...

  9. python基本数据类型之集合

    python基本数据类型之集合 集合是一种容器,用来存放不同元素. 集合有3大特点: 集合的元素必须是不可变类型(字符串.数字.元组): 集合中的元素不能重复: 集合是无序的. 在集合中直接存入lis ...

随机推荐

  1. Informatica

    安装 相关专题 关于Bulk加载模式 性能调优 性能瓶颈 性能瓶颈概览 性能瓶颈之Target 性能瓶颈之Source 性能瓶颈之Mapping 性能瓶颈之Session 性能瓶颈之System 性能 ...

  2. 安卓TabLayout+ViewPager实现切页

    安卓使用TabLayout+ViewPager+Fragment 实现页面切换,可实现左右滑动切换视图界面和点击切换 可自定义菜单栏是在顶部还是在底部 一.实现效果: 二.实现过程: 2.1 一些重要 ...

  3. linux性能优化参数小节

    总结一些和性能相关的常见参数 内核相关参数 位于/etc/sysctl.conf文件,向文件中添加 用sysctl -a可以查看默认配置 修改后可以通过sysctl -p执行并看看有没有错误 例如设置 ...

  4. Abp + MongoDb 改造默认的审计日志存储位置

    一.背景 在实际项目的开发当中,使用 Abp Zero 自带的审计日志功能写入效率比较低.其次审计日志数据量中后期十分庞大,不适合与业务数据存放在一起.所以我们可以重新实现 Abp 的 IAuditi ...

  5. 导入项目报错【Minimum supported Gradle version is 3.3. Current version is 2.14.1】

    问题描述 导入项目的时候,因为同事的开发环境是Android Studio 2.3.2  Gradle3.3.而我的开发环境是Android Studio 2.2.2 Gradle2.14.1. 所以 ...

  6. 全网最全的Windows下Anaconda2 / Anaconda3里正确下载安装OpenCV(离线方式和在线方式)(图文详解)

    不多说,直接上干货! 说明: Anaconda2-5.0.0-Windows-x86_64.exe安装下来,默认的Python2.7 Anaconda3-4.2.0-Windows-x86_64.ex ...

  7. DotNetCore深入了解之二HttpContext类

    当KestrelServer启动时,会绑定相应的IP地址,同时在绑定时将加入HttpConnectionMiddleware作为终端连接的中间件. public async Task StartAsy ...

  8. Servlet JSP 二重修炼:Filter过滤器

    摘要: 原创出处: http://www.cnblogs.com/Alandre/ 泥沙砖瓦浆木匠 希望转载,保留摘要,谢谢! 真正的朋友就是,当你蒙蔽了所有人的眼睛,也能看穿你真实的样子和心底的痛楚 ...

  9. Node.js 使用 RSA 做加密

    RSA RSA加密算法是一种非对称加密算法. 假设 A 与 B 通信.A 和 B 都提供一个公开的公钥.A 把需要传递的信息,先用自己的私钥签名,再用 B 的公钥加密.B 接收到这串密文后,用自己的私 ...

  10. Set存储元素为啥是唯一的(以HashSet为例源码分析)

    本文版权归 远方的风lyh和博客园共有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作,如有错误之处忘不吝批评指正! 说些废话 以前面试的时候会遇到有人问Set 和list的区别 这个很好答,但 ...