日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

collections之defaultdict

發(fā)布時間:2025/3/20 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 collections之defaultdict 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

最近在學習collections庫,做一點筆記。

1、基礎介紹

統(tǒng)計一個列表中元素出現(xiàn)的次數(shù)

#encoding:utf-8from collections import defaultdictusers = ["bobby1","bobby2","bobby3","bobby2","bobby4","bobby5","bobby4"] user_dic = {} #統(tǒng)計一下每個字段出現(xiàn)的次數(shù) # 方法一 for user in users:user_dic[user] += 1

很明顯因為在取user_dict['bobby1']的時候失敗,因為該dict中并無bobby1的key值,因此做以下修改

for user in users:if user not in user_dic:user_dic[user] = 1else:user_dic[user] += 1print(user_dic)

使用setdefault函數(shù)

for user in users:# user為鍵值user_dic.setdefault(user,0)user_dic[user] += 1print(user_dic)

那為什么setdefault有這個功能呢,查看其代碼

def setdefault(self, *args, **kwargs): # real signature unknown"""Insert key with a value of default if key is not in the dictionary.Return the value for key if key is in the dictionary, else default."""pass

即是如果key不在字典中,則插入key值;如果key在字典中,則返回key的值,否則返回default

接著對其再進行優(yōu)化

#encoding:utf-8from collections import defaultdictusers = ["bobby1","bobby2","bobby3","bobby2","bobby4","bobby5","bobby4"]default_dic = defaultdict(int) for user in users:default_dic[user] += 1print(default_dic)

因此針對以上特性,從而有對于Python中通過Key訪問字典,當Key不存在時,會引發(fā)‘KeyError’異常。為了避免這種情況的發(fā)生,可以使用collections類中的defaultdict()方法來為字典提供默認值。

defaultdict接受一個工廠函數(shù)作為參數(shù),如下來構造:

dict =defaultdict( factory_function)

這個factory_function可以是list、set、str等等,作用是當key不存在時,返回的是工廠函數(shù)的默認值,比如list對應[ ],str對應的是空字符串,set對應set( ),int對應0

使用list作第一個參數(shù),可以很容易將鍵-值對序列轉換為列表字典。

from collections import defaultdict s=[('yellow',1),('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] d=defaultdict(list) for k, v in s:d[k].append(v) a=sorted(d.items()) print(a)

2、規(guī)避字典中無鍵值的參數(shù)傳遞

其實我自己用的collections較多的是傳遞參數(shù)時,如果傳了該參數(shù)則使用參數(shù),如果沒有傳遞參數(shù)則使用默認值

from collections import defaultdictdef proposeIBPS101(newDic = {}):# receiptAccount=收方賬戶,amount=金額:tempDic = defaultdict(dict)tempDic.update(newDic)newDic = tempDicvalues = {"receiptAccount":"{}".format(62258487410258011 if not newDic["receiptAccount"] else newDic["receiptAccount"]),"amount":"{}".format(newDic["amount"])}print valuesif __name__ == '__main__':# ex1: 只傳遞一個參數(shù)newDic = {"amount":1.13}proposeIBPS101(newDic)# ex2:傳遞兩個參數(shù)newDic = {"receiptAccount":62258487410258022,"amount":1.13}proposeIBPS101(newDic)

輸出結果如下:

{'amount': '1.13', 'receiptAccount': '62258487410258011'} {'amount': '1.13', 'receiptAccount': '62258487410258022'}

在示例一種只傳遞了一個參數(shù),因此條件表達式中判斷為真,直接將默認參數(shù)62258487410258011 賦值給receiptAccount賬戶;第二個傳遞了賬戶,則直接使用傳遞的賬戶。

3、一個鍵多個值的字典

如何實現(xiàn)一個鍵對應多個值的字典,即是(multidict)?

之所以有這個問題是因為在讀取DB2的數(shù)據(jù)庫時,存在一個表對應的報文會登記兩條記錄,只是每個字段對應的值不同,常用的構造一鍵多值的形式如下:

dic1 = {'a':["paymentName","paymentAccount"],'b':["receiptName","receiptAccount"],}dic2 = {'a': {"paymentName", "paymentAccount"},'b': {"receiptName", "receiptAccount"},}

或者很方便的使用collections中的defaultdict來構造這樣的字典

tempDic = defaultdict(list)tempDic['a'].append("paymentName")tempDic['a'].append("paymentAccount")print(tempDic)

?

總結

以上是生活随笔為你收集整理的collections之defaultdict的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。