字典setdefault使用

2022-09-19 20:15:11 字數 1383 閱讀 9286

"""

字典setdefault方法的使用:

d.setdefault(k, [default]):

如果有k,則返回。如果沒有則讓 k = default,然會返回default

案例: 統計文字中每個單詞出現的位置

格式:

"""import re

import sys

# 返回pattern物件

word_re = re.compile(r'\w+') # [a-za-z0-9_]

index = {}

with open('./zen.txt', encoding='utf-8') as fp:

for line_no, line in enumerate(fp, 1): # 獲得行號和一行資料

for match in word_re.finditer(line): # 匹配每一行中的每個單詞

word = match.group()

column_no = match.start() + 1 # start() 該單詞在整個串中的位置

location = (line_no, column_no)

# occurrences = index.get(word, ) # <1>

# index[word] = occurrences # <3>

print(index)

for word in sorted(index, key=str.upper): # <4>

print(word, index[word])

zen.txt:

the zen of python, by tim peters

beautiful is better than ugly.

explicit is better than implicit.

輸出:

beautiful [(3, 1)]

better [(3, 14), (4, 13)]

by [(1, 20)]

explicit [(4, 1)]

implicit [(4, 25)]

is [(3, 11), (4, 10)]

of [(1, 9)]

peters [(1, 27)]

python [(1, 12)]

than [(3, 21), (4, 20)]

the [(1, 1)]

tim [(1, 23)]

ugly [(3, 26)]

zen [(1, 5)]

process finished with exit code 0

字典的setdefault方法

python 字典 setdefault 函式和get 方法類似,語法 dict.setdefault key,default value 如果鍵 key 不存在於字典中,將會新增鍵 key 並將值設為預設值 value 如果鍵 key 已經存在,則什麼也不做 例項 dict print value...

字典中setdefault 函式用法

python 字典中乙個 方法 setdefault 來看下說明 如果沒有 key 會加入 這個key setdefault key default 並且可以指定 乙個預設值,如果沒有指定,則認為是none 返回,如果 指定了default 則直接返回 default值 如果有這個key 直接返回字...

python中字典setdefault方法使用

經檢查,發現自己理解錯了需求,請忽略當前博文 像計算機科學家一樣思考python 11.10練習中 練習 11 2 閱讀字典方法setdefault的文件,並使用它來寫乙個更簡潔的invert dict def invert dict n 返回乙個列表,第一項用setdefault查詢使用者輸入的單...