最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Python中defaultdict的具體使用

 更新時間:2023年10月25日 08:10:07   作者:跡憶客  
defaultdict 是一個類似字典的容器,屬于 collections 模塊, 它是字典的子類, 因此它具有詞典的所有功能,下面小編就來和大家詳細(xì)聊聊defaultdict的具體使用吧

Python 中的 defaultdict 與 dict

defaultdict 是一個類似字典的容器,屬于 collections 模塊。 它是字典的子類; 因此它具有詞典的所有功能。 然而,defaultdict 的唯一目的是處理 KeyError。

# return true if the defaultdict is a subclass of dict (dictionary)
from collections import defaultdict
print(issubclass(defaultdict,dict))

輸出:

True

假設(shè)用戶在字典中搜索條目,并且搜索到的條目不存在。 普通字典會出現(xiàn)KeyError,表示該條目不存在。 為了解決這個問題,Python 開發(fā)人員提出了 defaultdict 的概念。

代碼示例:

# normal dictionary
ord_dict = {
    "x" :3,
    "y": 4
}

ord_dict["z"]   # --> KeyError

輸出:

KeyError: 'z'

普通字典無法處理未知鍵,當(dāng)我們搜索未知鍵時,它會拋出 KeyError,如上面的代碼所示。

另一方面,defaultdict 模塊的工作方式與 Python 詞典類似。 盡管如此,它仍然具有先進(jìn)、有用且用戶友好的功能,并且當(dāng)用戶在字典中搜索未定義的鍵時不會拋出錯誤。

相反,它在字典中創(chuàng)建一個條目,并針對該鍵返回一個默認(rèn)值。 為了理解這個概念,讓我們看看下面的實(shí)際部分。

代碼示例:

from collections import defaultdict

# the default value for the undefined key
def def_val():
    return "The searched Key Not Present"

dic = defaultdict(def_val)

dic["x"] = 3
dic["y"] = 4

# search 'z' in the dictionary 'dic'
print(dic["z"]) # instead of a KeyError, it has returned the default value
print(dic.items())

輸出:

The searched Key Not Present
dict_items([('x', 3), ('y', 4), ('z', 'The searched Key Not Present')])

defaultdict 創(chuàng)建我們嘗試使用該鍵訪問的任何項(xiàng)目,該鍵在字典中未定義。

并且創(chuàng)建這樣一個默認(rèn)項(xiàng),它調(diào)用我們傳遞給defaultdict的構(gòu)造函數(shù)的函數(shù)對象,更準(zhǔn)確地說,該對象應(yīng)該是一個包含類型對象和函數(shù)的可調(diào)用對象。

在上面的示例中,默認(rèn)項(xiàng)是使用 def_val 函數(shù)創(chuàng)建的,該函數(shù)根據(jù)字典中未定義的鍵返回字符串“搜索到的鍵不存在”。

Python 中的 defaultdict

default_factory 是 __missing__() 方法使用的 defaultdict 構(gòu)造函數(shù)的第一個參數(shù),如果構(gòu)造函數(shù)的參數(shù)丟失,default_factory 將被初始化為 None,這將出現(xiàn) KeyError。

如果 default_factory 是用 None 以外的東西初始化的,它將被分配為搜索到的鍵的值,如上面的示例所示。

Python 中 defaultdict 的有用函數(shù)

字典和defaultdict有很多功能。 我們知道,defaultdict可以訪問字典的所有功能; 然而,這些是 defaultdict 特有的一些最有用的函數(shù)。

Python 中的 defaultdict.clear()

代碼示例:

from collections import defaultdict

# the default value for the undefined key
def def_val():
    return "Not Present"

dic = defaultdict(def_val)

dic["x"] = 3
dic["y"] = 4

print(f'Before clearing the dic, values of x = {dic["x"]} and y = {dic["y"]}')
dic.clear() #dic.clear() -> None. it will remove all items from dic.
print(f'After clearing the dic, values of x = {dic["x"]} and y = {dic["y"]}')

輸出:

Before clearing the dic, values of x = 3 and y = 4
After clearing the dic, values of x = Not Present and y = Not Present

正如我們在上面的示例中看到的,字典 dic 中有兩對數(shù)據(jù),其中 x=3 和 y=4。 然而,使用 clear() 函數(shù)后,數(shù)據(jù)已被刪除,x和y的值不再存在,這就是為什么我們得到的x和y不存在。

Python 中的 defaultdict.copy()

代碼示例:

from collections import defaultdict

# the default value for the undefined key
def def_val():
    return "Not Present"

dic = defaultdict(def_val)

dic["x"] = 3
dic["y"] = 4

dic_copy = dic.copy() # dic.copy will give you a shallow copy of dic.

print(f"dic = {dic.items()}")
print(f"dic_copy = {dic_copy.items()}")

輸出:

dic = dict_items([('x', 3), ('y', 4)])
dic_copy = dict_items([('x', 3), ('y', 4)])

defaultdict.copy() 函數(shù)用于將字典的淺表副本復(fù)制到另一個我們可以相應(yīng)使用的變量中。

Python 中的 defaultdict.default_factory()

代碼示例:

from collections import defaultdict

# the default value for the undefined key
def def_val():
    return "Not present"

dic = defaultdict(def_val)

dic["x"] = 3
dic["y"] = 4

print(f"The value of z = {dic['Z']}")
print(dic.default_factory()) # default_factory returns the default value for defaultdict.

輸出:

The value of z = Not present
Not present

default_factory()函數(shù)用于為定義的類的屬性提供默認(rèn)值,一般情況下,default_factory的值是函數(shù)返回的值。

Python 中的 defaultdict.get(key, default value)

代碼示例:

from collections import defaultdict

# the default value for the undefined key
def def_val():
    return "Not present"

dic = defaultdict(def_val)

dic["x"] = 3
dic["y"] = 4

# search the value of Z in the dictionary dic; if it exists, return the value; otherwise, display the message
print(dic.get("Z","Value doesn't exist")) # default value is None

輸出:

Value doesn't exist

defaultdict.get() 函數(shù)有兩個參數(shù),第一個是鍵,第二個是鍵的默認(rèn)值,以防該值不存在。

但第二個參數(shù)是可選的。 所以我們可以指定任何消息或值; 否則,它將顯示 None 作為默認(rèn)值。

以上就是詳解Python中defaultdict的具體使用的詳細(xì)內(nèi)容,更多關(guān)于python defaultdict的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python多進(jìn)程同步Lock、Semaphore、Event實(shí)例

    Python多進(jìn)程同步Lock、Semaphore、Event實(shí)例

    這篇文章主要介紹了Python多進(jìn)程同步Lock、Semaphore、Event實(shí)例,Lock用來避免訪問沖突、Semaphore用來控制對共享資源的訪問數(shù)量、Event用來實(shí)現(xiàn)進(jìn)程間同步通信,需要的朋友可以參考下
    2014-11-11
  • python Crypto模塊的安裝與使用方法

    python Crypto模塊的安裝與使用方法

    本篇文章主要介紹了python Crypto模塊的安裝與使用方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12
  • 如何通過python檢查文件是否被占用

    如何通過python檢查文件是否被占用

    這篇文章主要介紹了如何通過python檢查文件是否被占用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • python使用pycharm環(huán)境調(diào)用opencv庫

    python使用pycharm環(huán)境調(diào)用opencv庫

    這篇文章主要介紹了python使用pycharm環(huán)境調(diào)用opencv庫,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-02-02
  • Scrapy之迭代爬取網(wǎng)頁中失效問題及解決

    Scrapy之迭代爬取網(wǎng)頁中失效問題及解決

    這篇文章主要介紹了Scrapy之迭代爬取網(wǎng)頁中失效問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • python實(shí)戰(zhàn)scrapy操作cookie爬取博客涉及browsercookie

    python實(shí)戰(zhàn)scrapy操作cookie爬取博客涉及browsercookie

    這篇文章主要為大家介紹了python實(shí)戰(zhàn)scrapy操作cookie爬取博客涉及browsercookie,下面來學(xué)習(xí)一下 scrapy 操作 Cookie來爬取博客吧
    2021-11-11
  • 在CMD命令行中運(yùn)行python腳本的方法

    在CMD命令行中運(yùn)行python腳本的方法

    今天小編就為大家分享一篇在CMD命令行中運(yùn)行python腳本的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • Python中調(diào)用其他程序的方式詳解

    Python中調(diào)用其他程序的方式詳解

    這篇文章主要介紹了Python中調(diào)用其他程序的方式詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • pytorch中的squeeze函數(shù)、cat函數(shù)使用

    pytorch中的squeeze函數(shù)、cat函數(shù)使用

    這篇文章主要介紹了pytorch中的squeeze函數(shù)、cat函數(shù)使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • Python存儲List數(shù)據(jù)到文件(text/csv/excel)幾種常見方法

    Python存儲List數(shù)據(jù)到文件(text/csv/excel)幾種常見方法

    在數(shù)據(jù)分析中經(jīng)常需要從csv格式的文件中存取數(shù)據(jù)以及將數(shù)據(jù)寫書到csv文件中,下面這篇文章主要給大家介紹了關(guān)于Python存儲List數(shù)據(jù)到文件(text/csv/excel)的幾種常見方法,需要的朋友可以參考下
    2024-02-02

最新評論

永川市| 昌邑市| 旺苍县| 鸡泽县| 富蕴县| 鄂托克前旗| 银川市| 香河县| 大连市| 灵寿县| 旺苍县| 武鸣县| 金坛市| 门源| 英吉沙县| 桐梓县| 聊城市| 海林市| 海阳市| 周口市| 广灵县| 阳朔县| 都昌县| 五峰| 永胜县| 山东| 孝昌县| 永宁县| 平山县| 淮阳县| 都昌县| 麦盖提县| 垦利县| 湾仔区| 湘潭县| 绥德县| 温州市| 湘潭市| 六枝特区| 普兰店市| 五莲县|