網站首頁 編程語言 正文
用法講解:
- 一般情況下,在使用字典時,先定義一個空字典(如dict_a = {}),然后往字典中添加元素只需要 dict_a[key] = value即可。讀取字典中的元素時同理,但前提時字典中存在這個key,否則就會報錯。
- 而defaultdict()的作用在于,即使字典中的key不存在,在查找時也會對它的value賦予一個默認值,從而避免了報錯。
- 具體來說,defaultdict接受一個工廠函數作為參數,如下來構造:
dict =defaultdict(factory_function)
- 這個factory_function可以是list、set、str等等,作用是當key不存在時,返回的是工廠函數的默認值,比如list對應[ ],str對應的是空字符串,set對應set( ),int對應0。
from collections import defaultdict
dict1 = defaultdict(int) # dict1[1]=0
dict2 = defaultdict(set) # dict2[1]=set()
dict3 = defaultdict(str) # dict3[1]=
dict4 = defaultdict(list) # dict4[1]=[
應用舉例: 題目描述:
1. 不使用defaultdict():?
def isAnagram(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict_s = {}
for item in s:
if item not in dict_s.keys():
dict_s[item] = 1
else:
dict_s[item] += 1
dict_t = {}
for item in t:
if item not in dict_t.keys():
dict_t[item] = 1
else:
dict_t[item] += 1
return dict_s == dict_t
2. 使用defaultdict():?
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
from collections import defaultdict
dict_s = defaultdict(int)
dict_t = defaultdict(int)
for item in s:
dict_s[item] += 1
for item in t:
dict_t[item] += 1
return dict_s == dict_t
參考:https://www.jianshu.com/p/bbd258f99fd3?
原文鏈接:https://blog.csdn.net/m0_46483236/article/details/125609403
相關推薦
- 2024-01-30 MongoDB 聚合查詢在數據統計中的應用
- 2022-04-12 git bash 管理員權限_liunx安裝zsh、oh-my-zsh(無root權限安裝)
- 2022-11-01 AndroidView與Compose框架交互實現介紹_Android
- 2022-07-13 CSS 不需要清除浮動的圣杯布局~面試可能會問
- 2022-10-08 詳解C語言如何實現雙向帶頭循環鏈表_C 語言
- 2022-07-22 python:實現打印從 0 到 n 的卡特蘭數算法(附完整源碼)
- 2022-04-09 python多線程互斥鎖與死鎖問題詳解_python
- 2022-01-30 tortoiseGit推送每次需要輸入密碼,解決方案
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支