当前位置:网站首页>好用的字典-defaultdict
好用的字典-defaultdict
2022-06-24 23:49:00 【向上的阿鹏】
参考链接:https://blog.csdn.net/sGDUTBMW/article/details/108962367
defaultdict类就好像是一个dict,但是它是使用一个类型来初始化的;
defaultdict类的初始化函数接受一个类型作为参数,当所访问的键不存在的时候,可以实例化一个值作为默认值;如空值。
相比于dict,所访问的键不存在时,不会报错,只会返回一个默认值,除此之外,在使用dict的过程中,相同key只能保存一个value,当存在重复的key时,会覆盖value,不利于寻找相同key多个value的情况,而defaultdict则可以是返回多个value值。
例子:

输出:
defaultdict类除了接受类型名称作为初始化函数的参数之外,还可以使用任何不带参数的可调用函数,到时该函数的返回结果作为默认值,这样使得默认值的取值更加灵活
from collections import defaultdict
strings = ('puppy', 'kitten', 'puppy', 'puppy',
'weasel', 'puppy', 'kitten', 'puppy')
def zero():
return 0
connts = defaultdict(zero) # 使用自定义的不带参的zero函数
counts = defaultdict(lambda: 0) # 使用lambda来定义简单的函数,效果同上
for s in strings:
counts[s] += 1
print(counts)
输出:
边栏推荐
- AI自己写代码让智能体进化!OpenAI的大模型有“人类思想”那味了
- 给你讲懂 MVCC 续篇
- 微信小程序获取扫描二维码后携带的参数
- 小米路由R4A千兆版安装breed+OpenWRT教程(全脚本无需硬改)
- 国信金太阳打新债步骤 开户是安全的吗
- Practice and Thinking on process memory
- Smartctl opens the device and encounters permission denied problem troubleshooting process record
- Refresh mechanism of vie
- 把 Oracle 数据库从 Windows 系统迁移到 Linux Oracle Rac 集群环境(1)——迁移数据到节点1
- VSCode中如何实现点击DOM自动定位到相应代码行
猜你喜欢

Unity存档系统——Json格式的文件

Refresh mechanism of vie

PyTorch学习笔记(七)------------------ Vision Transformer

Application of TSDB in civil aircraft industry

Sumati gamefi ecological overview, element design in the magical world

用向量表示两个坐标系的变换

Detailed explanation of cache (for the postgraduate entrance examination of XD)

自动化测试

软件测试周刊(第77期):只要放弃一次,就会滋生放弃的习性, 原本可以解决的问题也会变得无法解决。

DSPACE设置斑马线和道路箭头
随机推荐
Unity存档系统——Json格式的文件
How to uninstall CUDA
【STL源码剖析】配置器(待补充)
Planification du réseau | [quatre couches de réseau] points de connaissance et exemples
CUDA编程入门极简教程
Insurance can also be bought together? Four risks that individuals can pool enough people to buy Medical Insurance in groups
Using qdomdocument to manipulate XML files in QT
NPM package publishing tutorial
Getting started with unityshader - Surface Shader
Leetcode 210: curriculum II (topological sorting)
Is it out of reach to enter Ali as a tester? Here may be the answer you want
Software testing salary in first tier cities - are you dragging your feet
Internship: use of SVN
CMakeLists中的add_definitions()函数
运行时修改Universal Render Data
It is said that Yijia will soon update the product line of TWS earplugs, smart watches and bracelets
ACL access control of squid proxy server
背了八股文,六月赢麻了……
调用系统函数安全方案
保险也能拼购?个人可以凑够人数组团购买医疗保险的4大风险