日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
default在python

在Python中,defaultdict是一個非常實用的內(nèi)置字典子類,它可以自動為字典中不存在的鍵生成默認(rèn)值,這樣可以避免因為訪問不存在的鍵而產(chǎn)生的KeyError。defaultdict的使用非常簡單,下面將詳細(xì)介紹其用法。

創(chuàng)新互聯(lián)專注于準(zhǔn)格爾網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗。 熱誠為您提供準(zhǔn)格爾營銷型網(wǎng)站建設(shè),準(zhǔn)格爾網(wǎng)站制作、準(zhǔn)格爾網(wǎng)頁設(shè)計、準(zhǔn)格爾網(wǎng)站官網(wǎng)定制、小程序制作服務(wù),打造準(zhǔn)格爾網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供準(zhǔn)格爾網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。

1、引入defaultdict

需要從collections模塊中引入defaultdict。

from collections import defaultdict

2、創(chuàng)建defaultdict對象

創(chuàng)建defaultdict對象時,需要傳入一個可調(diào)用對象(如函數(shù)、類等),這個可調(diào)用對象用于生成默認(rèn)值,我們可以創(chuàng)建一個整數(shù)默認(rèn)值為0的defaultdict

d = defaultdict(int)

3、使用defaultdict

當(dāng)我們訪問defaultdict中不存在的鍵時,它會自動調(diào)用傳入的可調(diào)用對象生成默認(rèn)值。

print(d["a"])  # 輸出:0

當(dāng)我們對不存在的鍵進(jìn)行加法操作時,也會自動生成默認(rèn)值:

d["b"] += 1
print(d["b"])  # 輸出:1

4、自定義默認(rèn)值生成函數(shù)

我們還可以根據(jù)需要自定義默認(rèn)值生成函數(shù),我們可以創(chuàng)建一個字符串默認(rèn)值為"unknown"的defaultdict

def unknown_string():
    return "unknown"
d = defaultdict(unknown_string)

當(dāng)我們訪問不存在的鍵時,它會返回"unknown":

print(d["c"])  # 輸出:"unknown"

5、使用defaultdict處理字典列表

defaultdict還可以方便地處理字典列表,我們可以統(tǒng)計一個字符串列表中每個字符出現(xiàn)的次數(shù):

s = "hello world"
word_count = defaultdict(int)
for word in s:
    word_count[word] += 1
print(word_count)  # 輸出:defaultdict(, {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

6、使用defaultdict處理嵌套字典

defaultdict還可以方便地處理嵌套字典,我們可以創(chuàng)建一個二維坐標(biāo)系,并統(tǒng)計每個坐標(biāo)點(diǎn)上有多少個點(diǎn):

points = [(1, 2), (3, 4), (1, 2), (5, 6), (3, 4)]
coordinate_count = defaultdict(lambda: defaultdict(int))
for x, y in points:
    coordinate_count[x][y] += 1
print(coordinate_count)  # 輸出:defaultdict( at 0x7f8c1c2d6d30>, {1: defaultdict(, {2: 2}), 3: defaultdict(, {4: 2}), 5: defaultdict(, {6: 1})})

defaultdict是Python中的一個非常實用的內(nèi)置字典子類,它可以自動為字典中不存在的鍵生成默認(rèn)值,從而避免因為訪問不存在的鍵而產(chǎn)生的KeyError,使用defaultdict可以讓我們更加簡潔、高效地處理字典數(shù)據(jù)。


網(wǎng)站標(biāo)題:default在python
文章鏈接:http://m.5511xx.com/article/cdjdoch.html