python collections 中的 Counter, defaultdict, OrderedDict, namedtuple, deque
1 Counter
计数,以下的例子,找出列表中元素的重复次数:
from collections import Counterdevice_temperatures = [13.5, 14.0, 14.0, 14.5, 14.5, 14.5, 15.0, 16.0]temperature_counter = Counter(device_temperatures)# Counter({14.5: 3, 14.0: 2, 13.5: 1, 15.0: 1, 16.0: 1})
print(temperature_counter)
print(type(temperature_counter)) # <class 'collections.Counter'>
print(temperature_counter[13.5]) # 1
print(temperature_counter[14.0]) # 2
print(temperature_counter[14.5]) # 3
print(temperature_counter[15.0]) # 1
print(temperature_counter[16.0]) # 1
2 defaultdict
例 1
如下的代码将产生错误 KeyError
,因为 my_dict
里没有为 'hi'
的 key:
my_dict={'hello':5}
print(my_dict['hi'])# Traceback (most recent call last):
# File "<string>", line 4, in <module>
# KeyError: 'hi'
# >
与之相反, defaultdict
从不会引发 KeyError
。
以下是一个由 tuple 组成的列表 coworkers
,列出了每个人就读过的学校:
coworkers = [('Rolf', 'MIT'), ('Jen', 'Oxford'), ('Rolf', 'Cambridge'), ('Charlie', 'Manchester')]
现在要得到一个dictionary:
{'Rolf': ['MIT', 'Cmbridge'],'Jen': ['Oxford'],'Charlie': ['Manchester']
}
一般的写法:
coworkers = [('Rolf', 'MIT'), ('Jen', 'Oxford'), ('Rolf', 'Cambridge'), ('Charlie', 'Manchester')]
alma_maters = {} # (alma mater:母校)
for coworker in coworkers:if coworker[0] not in alma_maters:alma_maters[coworker[0]] = []alma_maters[coworker[0]].append(coworker[1])
或者:
coworkers = [('Rolf', 'MIT'), ('Jen', 'Oxford'), ('Rolf', 'Cambridge'), ('Charlie', 'Manchester')]
alma_maters = {} # (alma mater:母校)
for coworker, place in coworkers:if coworker not in alma_maters:alma_maters[coworker] = [] # default valuealma_maters[coworker].append(place)print(alma_maters)
改为使用 defaultdict
:
from collections import defaultdictcoworkers = [('Rolf', 'MIT'), ('Jen', 'Oxford'), ('Rolf', 'Cambridge'), ('Charlie', 'Manchester')]
# 如果词典中的某一个key不存在,则调用参数里的function
# 这里 function 是 list,即调用list,得到一个空的列表 []
alma_maters = defaultdict(list)
for coworker, place in coworkers:alma_maters[coworker].append(place)# 如果希望在访问不存在的 key 时,能引发异常, 则添加下面的一行
# alma_maters.default_factory = None
# (None 改成 int 时生成 0 值)print(alma_maters['Rolf']) # ['MIT', 'Cambridge']
print(alma_maters['Jen']) # ['Oxford']
print(alma_maters['Charlie']) # ['Manchester']
print(alma_maters['Anne']) # []
例 2
from collections import defaultdictmy_company = 'Teclado'coworkers = ['Jen', 'Li', 'Charlie', 'Rhys']
other_coworkers = [('Rolf', 'Apple Inc.'), ('Anna', 'Google')]# 不能直接写 my_company, 因为 defaultdict 接受函数为参数
# lambda: my_company 返回 my_company
coworker_companies = defaultdict(lambda: my_company)for person, company in other_coworkers:coworker_companies[person] = company# coworkers[1] 是 'Li', 输出默认值 Teclado
print(coworker_companies[coworkers[1]]) # other_coworkers[0][0] 是 'Rolf', 输出 Apple Inc.
print(coworker_companies[other_coworkers[0][0]])
3 OrderedDict
这里是 Pascal Case
顾名思义,OrderedDict 是有序词典,是指键值对的顺序按插入顺序排序。
from collections import OrderedDicto = OrderedDict()
o['Rolf'] = 6
o['Jose'] = 10
o['Jen'] = 3# keys are always in the order in which they were inserted
# OrderedDict([('Rolf', 6), ('Jose', 10), ('Jen', 3)])
print(o) o.move_to_end('Rolf') # 移到末尾
# OrderedDict([('Jose', 10), ('Jen', 3), ('Rolf', 6)])
print(o) o.move_to_end('Rolf', last = False) # 移到反向的末尾,即开头
# OrderedDict([('Rolf', 6), ('Jose', 10), ('Jen', 3)])
print(o)o.popitem()# OrderedDict([('Rolf', 6), ('Jose', 10)])
print(o)
o.popitem(False)
: 删除开头的元素
但从 Python 3.7 开始,dictionary 已经按插入排序,所以 OrderedDict
用处不是特别大。
Are dictionaries ordered in Python 3.6+?
4 namedtuple
namedtuple
: 给 tuple 以及 tuple 中的每一个元素都取名字
如下的代码,account[0]
,account[1]
分别指的什么不是显而易见:
account = ('checking', 1850.90)print(account[0]) # name
print(account[1]) # balance
使用 namedtuple
:
from collections import namedtupleaccount = ('checking', 1850.90)# 第1个参数是 tuple 名称,和定义名称相同
# 第2个参数是 fields 名称
Account = namedtuple("Account", ['name', 'balance'])accountNamedTuple_1 = Account('checking', 1850.90)
print(accountNamedTuple_1.name, accountNamedTuple_1.balance) # checking 1850.9accountNamedTuple_2 = Account._make(account)
account_name_2, account_balance_2 = accountNamedTuple_2
print(account_name_2, account_balance_2) # checking 1850.9accountNamedTuple_3 = Account(*account)
account_name_3, account_balance_3 = accountNamedTuple_3
print(account_name_3, account_balance_3) # checking 1850.9print(accountNamedTuple_1._asdict()['balance']) # 1850.9
print(accountNamedTuple_2._asdict()['balance']) # 1850.9
print(accountNamedTuple_3._asdict()['balance']) # 1850.9
从 csv 文件或者 database 读取数据时,使用 namedtuple
可使代码更容易理解。
5 deque
deque
:double ended queue 双端队列,使用deque
而非 list
的原因首先是deque
效率高,其次它保证线程安全 (thread safe),deque
所有的操作都是线程安全的 ,因此在使用 thread 时可使用 deque
。
from collections import dequefriends = deque(('Rolf', 'Charlie', 'Jen', 'Anna'))friends.append('Jose')
friends.appendleft('Anthony')
print(friends) # deque(['Anthony', 'Rolf', 'Charlie', 'Jen', 'Anna', 'Jose'])friends.pop()
print(friends) # deque(['Anthony', 'Rolf', 'Charlie', 'Jen', 'Anna'])friends.popleft()
print(friends) # deque(['Rolf', 'Charlie', 'Jen', 'Anna'])
python collections 中的 Counter, defaultdict, OrderedDict, namedtuple, deque相关推荐
- python3 开发面试题(collections中的Counter)6.7
''' 编写Python脚本,分析xx.log文件,按域名统计访问次数xx.log文件内容如下: https://www.sogo.com/ale.html https://www.qq.com/3a ...
- python中collections中的counter类_了解Python的collections.Counter类型
python视频教程栏目介绍Python的collections.Counter类型. collections.Counter 类型可以用来给可散列的对象计数,或者是当成多重集合来使用 -- 多重集合 ...
- python中采用字典建立统,Python中使用Counter进行字典创建以及key数量统计的方法...
这里的Counter是指collections中的Counter,通过Counter可以实现字典的创建以及字典key出现频次的统计.然而,使用的时候还是有一点需要注意的小事项. 使用Counter创建 ...
- python如何统计字典里面健的数量_Python中使用Counter进行字典创建以及key数量统计的方法...
Python中使用Counter进行字典创建以及key数量统计的方法 来源:中文源码网 浏览: 次 日期:2018年9月2日 Python中使用Counter进行字典创建以及key数量统计 ...
- Python的重要模块:collections (namedtuple、defaultdict、deque、Counter、OrderedDict、ChainMap)
collections 模块作用 包含双端队列 deque.默认字典 defaultdict.命名元组 namedtuple.计数器 Counter.Ordereddict 和 ChainMap 等重 ...
- python︱ collections模块(namedtuple/defaultdict/OrderedDict等)
collections有的功能: ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList', 'UserString',\'Count ...
- Python中Collections模块的Counter容器类使用教程
Python中Collections模块的Counter容器类使用教程 1.collections模块 collections模块自Python2.4版本开始被引入,包含了dict,set,list, ...
- Python标准库——collections模块的Counter类
更多16 最近在看一本名叫<Python Algorithm: Mastering Basic Algorithms in the Python Language>的书,刚好看到提到这个C ...
- Python标准库collections中与字典有关的类
Python标准库中提供了很多扩展功能,大幅度提高了开发效率.这里主要介绍OrderedDict类.defaultdict类和Counter类. (1)OrderedDict类 Python内置字典d ...
最新文章
- 压缩感知的阶段性总结
- powerdesigner显示列描述信息
- python哨兵循环_Python:deadloop之非模态交互界面(模态循环)(哨兵循环)
- 设置linearlayout最大高度_高位消防水箱设置要求及历年真题
- .NET跨平台之Sake和KoreBuild
- MySQL划重点-查询-条件
- 最新!北京电影学院成立“翟天临事件”调查组
- 中软python编码规范考试试题_这些常见的python学习问题,你中枪了吗?
- python网站服务器好麻烦_python写的网站,云服务器经常无法访问
- LeetCode 504. Base 7 (C++)
- python爬虫新闻网页的浏览量转载量,Python爬取新闻网标题、日期、点击量
- 20191202_2_识别偷税漏税人
- 20170317起mvc功能学习
- 多轮对话机器之话题意图识别
- 【R语言】结巴分词与词性提取(以“提取知乎问题标题的频繁词前100个形容词”实战为例)(3月25日学习笔记)
- 分享一个代码合并工具
- android 键盘挡住popupwindow,软键盘遮挡住popupWindow问题
- 浅谈留存率到底有多少种统计方式(口径问题)
- 微博数据:如何在西瓜微数平台使用「热门话题分析」功能?
- 算法题解01——对分搜索求立方根