python字典默认输出键还是值_说说在 Python 字典中如何在读取不存在的键时得到一个默认值...
如果有方法能夠在 Python 字典類型中,當讀取不存在的鍵時能夠得到一個默認值,那么代碼就會變得更加直觀。通過 defaultdict 類型可以實現這個目的1。
我們來改寫一個 “輸出單詞所在坐標” 的示例來說明使用 defaultdict 類型與使用 setDefault 方法之間的區別2。
改寫后的完整示例代碼如下:
import collections
import logging
logging.basicConfig(level=logging.DEBUG, format='%(levelname)s - %(message)s')
'''
defaultdict 示例
:author:Deniro Lee
'''
import sys
import re
WORD_RE = re.compile(r'\w+')
index = collections.defaultdict(list)
with open(sys.argv[1], 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
location = (line_no, column_no)
index[word].append(location)
for word in sorted(index, key=str.upper):
logging.info('word -> %s;index[word] -> %s', word, index[word])
部分運行結果:
INFO - word -> a;index[word] -> [(1, 7), (1, 46), (1, 76), (1, 111), (3, 52), (3, 87), (19, 75), (19, 162)]
INFO - word -> about;index[word] -> [(9, 83)]
INFO - word -> acknowledged;index[word] -> [(1, 27)]
我們把這兩種方法在示例中實際區別列舉出來,這樣看的更清楚。
使用 setDefault 方法:
index = {}
...
index.setdefault(word, []).append(location)
...
使用 defaultdict 類型:
index = collections.defaultdict(list)
index[word].append(location)
相對來說,defaultdict 類型的寫法比使用 setDefault 方法的寫法更加直觀。
在 index[word] 表達式中,如果 word 在 index 中不存在,即字典的某個鍵不存在,那么會新建一個 list 作為 word 的值,并以 word 為鍵一并放入 index 字典中,相當于初始化操作。所以示例中可以直接把 location 對象append 到 index[word] 表達式中。
參考資料:
【1】Luciano Ramalho (作者),安道,吳珂 (譯者).流暢的Python.人民郵電出版社,2017:143-145.
【2】說說在 Python 中如何使用 setDefault 方法提高效率.
總結
以上是生活随笔為你收集整理的python字典默认输出键还是值_说说在 Python 字典中如何在读取不存在的键时得到一个默认值...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: broker可以禁用吗 time_很多人
- 下一篇: python启动mysql_Python