Python基礎(chǔ)語法中defaultdict的使用小結(jié)
Python的defaultdict是collections模塊中提供的一種特殊的字典類型,它與普通的字典(dict)有著相似的功能,但有一個(gè)關(guān)鍵的不同點(diǎn):當(dāng)訪問一個(gè)不存在的鍵時(shí),defaultdict不會(huì)拋出KeyError異常,而是會(huì)自動(dòng)為該鍵創(chuàng)建一個(gè)默認(rèn)值。這種特性使得在處理需要初始化新鍵的情況時(shí)更加方便。
創(chuàng)建defaultdict要使用defaultdict,首先需要從collections模塊導(dǎo)入它:
from collections import defaultdict
然后可以創(chuàng)建一個(gè)defaultdict實(shí)例,傳入一個(gè)可調(diào)用對(duì)象作為default_factory參數(shù)。
這個(gè)可調(diào)用對(duì)象決定了當(dāng)訪問不存在的鍵時(shí)應(yīng)該返回的默認(rèn)值類型。
例如:
- 使用
int作為default_factory將返回整數(shù)0。 - 使用
list作為default_factory將返回空列表[]。 - 使用
set作為default_factory將返回空集合set()。 - 使用自定義函數(shù)作為
default_factory將根據(jù)該函數(shù)的返回值來確定默認(rèn)值。
示例1
from collections import defaultdict
bag = ['apple', 'orange', 'cherry', 'apple','apple', 'cherry', 'blueberry']
count = defaultdict(int) # 使用int作為default_factory
print(f"\n > > > > > > count:\n {count}")
print(f"\n > > > > > > type(count):\n {type(count)}")
for fruit in bag:
count[fruit] += 1
print(f"\n > > > > > > count:\n {count}")
輸出:
> > > > > > count:
defaultdict(<class 'int'>, {})> > > > > > type(count):
<class 'collections.defaultdict'>> > > > > > count:
defaultdict(<class 'int'>, {'apple': 3, 'orange': 1, 'cherry': 2, 'blueberry': 1})
在這個(gè)例子中,對(duì)一個(gè)不存在的鍵進(jìn)行操作時(shí),defaultdict會(huì)自動(dòng)為該鍵分配一個(gè)默認(rèn)值0,并允許直接對(duì)其進(jìn)行遞增操作。
示例2
from collections import defaultdict
names = [('group1', 'Alice'), ('group2', 'Bob'), ('group1', 'Charlie')]
grouped_names = defaultdict(list)
print(f"\n > > > > > > grouped_names:\n {grouped_names}")
print(f"\n > > > > > > type(grouped_names):\n {type(grouped_names)}")
for group, name in names:
grouped_names[group].append(name)
print(f"\n > > > > > > grouped_names:\n {grouped_names}")
輸出:
> > > > > > grouped_names:
defaultdict(<class 'list'>, {})> > > > > > type(grouped_names):
<class 'collections.defaultdict'>> > > > > > grouped_names:
defaultdict(<class 'list'>, {'group1': ['Alice', 'Charlie'], 'group2': ['Bob']})
在這個(gè)例子中,根據(jù)第一個(gè)元素對(duì)名字進(jìn)行了分組。如果使用普通字典,則需要額外的邏輯來檢查和初始化每個(gè)新組。
到此這篇關(guān)于Python基礎(chǔ)語法中defaultdict的使用小結(jié)的文章就介紹到這了,更多相關(guān)Python defaultdict內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)將Excel內(nèi)容批量導(dǎo)出為PDF文件
這篇文章主要為大家介紹了如何利用Python實(shí)現(xiàn)將Excel表格內(nèi)容批量導(dǎo)出為PDF文件,文中的實(shí)現(xiàn)步驟講解詳細(xì),感興趣的小伙伴可以了解一下2022-04-04
python實(shí)現(xiàn)密碼強(qiáng)度校驗(yàn)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)密碼強(qiáng)度校驗(yàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03
終端能到import模塊 解決jupyter notebook無法導(dǎo)入的問題
這篇文章主要介紹了在終端能到import模塊 而在jupyter notebook無法導(dǎo)入的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03
python GUI庫圖形界面開發(fā)之PyQt5滾動(dòng)條控件QScrollBar詳細(xì)使用方法與實(shí)例
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5滾動(dòng)條控件QScrollBar詳細(xì)使用方法與實(shí)例,需要的朋友可以參考下2020-03-03
python構(gòu)建基礎(chǔ)的爬蟲教學(xué)
在本篇內(nèi)容里小編給大家分享的是關(guān)于python構(gòu)建基礎(chǔ)的爬蟲教學(xué)內(nèi)容,需要的朋友們學(xué)習(xí)下。2018-12-12

