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

詳解Python中defaultdict的具體使用

 更新時間:2023年10月25日 08:10:07   作者:跡憶客  
defaultdict 是一個類似字典的容器,屬于 collections 模塊, 它是字典的子類, 因此它具有詞典的所有功能,下面小編就來和大家詳細聊聊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

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

代碼示例:

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

ord_dict["z"]   # --> KeyError

輸出:

KeyError: 'z'

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

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

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

代碼示例:

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)建我們嘗試使用該鍵訪問的任何項目,該鍵在字典中未定義。

并且創(chuàng)建這樣一個默認項,它調用我們傳遞給defaultdict的構造函數的函數對象,更準確地說,該對象應該是一個包含類型對象和函數的可調用對象。

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

Python 中的 defaultdict

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

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

Python 中 defaultdict 的有用函數

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

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 中有兩對數據,其中 x=3 和 y=4。 然而,使用 clear() 函數后,數據已被刪除,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() 函數用于將字典的淺表副本復制到另一個我們可以相應使用的變量中。

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()函數用于為定義的類的屬性提供默認值,一般情況下,default_factory的值是函數返回的值。

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() 函數有兩個參數,第一個是鍵,第二個是鍵的默認值,以防該值不存在。

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

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

相關文章

  • Python多進程同步Lock、Semaphore、Event實例

    Python多進程同步Lock、Semaphore、Event實例

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

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

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

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

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

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

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

    Scrapy之迭代爬取網頁中失效問題及解決

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

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

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

    在CMD命令行中運行python腳本的方法

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

    Python中調用其他程序的方式詳解

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

    pytorch中的squeeze函數、cat函數使用

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

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

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

最新評論

讷河市| 鄯善县| 东乡族自治县| 吕梁市| 横山县| 南平市| 盐源县| 清新县| 静宁县| 志丹县| 武邑县| 长治县| 杭锦后旗| 彝良县| 广南县| 南充市| 阿荣旗| 霍城县| 阳泉市| 古丈县| 铜山县| 洛扎县| 高要市| 霸州市| 金山区| 澜沧| 石家庄市| 纳雍县| 泰州市| 彝良县| 麻江县| 双峰县| 广宁县| 策勒县| 雷州市| 新野县| 会理县| 永丰县| 韶山市| 高州市| 句容市|