Python基礎語法中defaultdict的使用小結(jié)
Python的defaultdict是collections模塊中提供的一種特殊的字典類型,它與普通的字典(dict)有著相似的功能,但有一個關鍵的不同點:當訪問一個不存在的鍵時,defaultdict不會拋出KeyError異常,而是會自動為該鍵創(chuàng)建一個默認值。這種特性使得在處理需要初始化新鍵的情況時更加方便。
創(chuàng)建defaultdict要使用defaultdict,首先需要從collections模塊導入它:
from collections import defaultdict
然后可以創(chuàng)建一個defaultdict實例,傳入一個可調(diào)用對象作為default_factory參數(shù)。
這個可調(diào)用對象決定了當訪問不存在的鍵時應該返回的默認值類型。
例如:
- 使用
int作為default_factory將返回整數(shù)0。 - 使用
list作為default_factory將返回空列表[]。 - 使用
set作為default_factory將返回空集合set()。 - 使用自定義函數(shù)作為
default_factory將根據(jù)該函數(shù)的返回值來確定默認值。
示例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})
在這個例子中,對一個不存在的鍵進行操作時,defaultdict會自動為該鍵分配一個默認值0,并允許直接對其進行遞增操作。
示例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']})
在這個例子中,根據(jù)第一個元素對名字進行了分組。如果使用普通字典,則需要額外的邏輯來檢查和初始化每個新組。
到此這篇關于Python基礎語法中defaultdict的使用小結(jié)的文章就介紹到這了,更多相關Python defaultdict內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python實現(xiàn)將Excel內(nèi)容批量導出為PDF文件
這篇文章主要為大家介紹了如何利用Python實現(xiàn)將Excel表格內(nèi)容批量導出為PDF文件,文中的實現(xiàn)步驟講解詳細,感興趣的小伙伴可以了解一下2022-04-04
終端能到import模塊 解決jupyter notebook無法導入的問題
這篇文章主要介紹了在終端能到import模塊 而在jupyter notebook無法導入的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
python GUI庫圖形界面開發(fā)之PyQt5滾動條控件QScrollBar詳細使用方法與實例
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5滾動條控件QScrollBar詳細使用方法與實例,需要的朋友可以參考下2020-03-03

