0
0

More than 1 year has passed since last update.

【Python】 defaultdictを使ってリストの集計をする

Last updated at Posted at 2022-07-09

この記事は筆者が勉強したことを、自分のなかで理解を深めるために書いています。
間違った解釈、表現などありましたら、コメントいただけますと幸いです。

辞書型のおさらい

d = {key1 : value1, key2 : value2, key3 : value3,...}

・要素(value)へのアクセスはkeyを使って参照
・一つの辞書の中に同じkeyを重複して持たせることはできない
・集合と同じく、可変、重複なし、順番なし

defaultdict()について

・辞書型を拡張したデータ型
・キーが存在しない要素にアクセスした時の挙動を定義しておくことができる

defaultdict()の使用例 ~リストを集計する~

main.py
# collectionsモジュールからdefaultdictを読み込む
from collections import defaultdict
# リスト
results = ["tomato", "tomato", "potato", "tomato", "potato", "tomato"]

# 関数の定義
def init():
    return 0 #とにかく0を返す

# ()の中にキーが存在しない要素にアクセスしたときに0を返すように設定
# 関数を渡すことになっているので上記defにて定義
stats = defaultdict(init)
for result in results:
    stats[result] += 1 # リストの中のtomatoとpotato数える

print(stats)
main.pyを実行・出力結果
~ $ python main.py
defaultdict(<function init at 0x7fa268a7d9>, {'tomato': 4, 'potato': 2}) # 集計結果
~ $ 

「function init at 0x7fa268a7d9」の0x7fa268a7d9はメモリ番地

lambda・intを使って短く表現する

defaultdict の引数には、「単に0を返す処理」を記述する。

つまり「0を返す関数」になるので、初期値が 0 になる。
以下2つは、どちらも0を返す。
・lambda: 0
・defaultdict(int)

main.py
from collections import defaultdict
results = ["tomato", "tomato", "potato", "tomato", "potato", "tomato"]

# 単に0を返す処理、intは引数なしで渡すと必ず0を返す
# int:組み込み関数、整数型に変換する
stats = defaultdict(int)
# 引数がなく、return一行の処理なので、lambdaで短く表現可能
# stats = defaultdict(lambda: 0)、こちらも0を返す

for result in results:
    stats[result] += 1

# 辞書型で表示、組み込み関数のdict()を使う
print(dict(stats))
main.pyを実行・出力結果
~ $ python main.py
{'pass': 4, 'fail': 2}
~ $ 

参考にしたサイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0