Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

DefaultDict

預設的值。

collections.defaultdict在宣告時會給預設值。

背景知識

dict需要key, value
傳統dict

1
2
3
4
5
6
7
8
9
10
11
12
13
res = dict()
res['key']
print(res)
> KeyError: 'key'

res = dict()
res['key'] = 3
print(res)
> {'key': 3}

dic1 = {}
dic1["k1"].append("kkkkk") #error
print(dic1)

改defaultDict

1
2
3
4
5
6
7
8
9
10
11
12
from collections import defaultdict
res = defaultdict(list) # ()內一定要指定型別
res['key']
print(res)
>>defaultdict(<class 'list'>, {'key': []})

import collections
dic = collections.defaultdict(list) #list
dic["k1"].append("kkkkk")
print(dic)

> defaultdict(<class 'list'>, {'k1': ['kkkkk']})

理解問題

DefaultDict統計字元次數,並與counter比較。

思路視覺化

遇到相同字元+1

程式化

  • 統計字元數int
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import collections
# from collections import defaultdict, Counter

C = collections.defaultdict(int) # 0開始
# collections.Counter()
# list(C) # 列出key值


s="AABBABC"
for v in s:
C[v]+=1
print(C)

> defaultdict(<class 'int'>, {'A': 3, 'B': 3, 'C': 1})
# Counter({'A': 3, 'B': 3, 'C': 1})

  • 合併群組set
1
2
3
4
5
6
7
s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
d = defaultdict(set)
for k, v in s:
d[k].add(v)
print(d)

>defaultdict(<class 'set'>,'red': , {1, 3}, 'blue': {2, 4})
  • 合併開頭字元相同字串list
1
2
3
4
5
6
7
8
9
words = ['apple', 'pear', 'peach', 'banana', 'plum']
by_letter = defaultdict(list)

for word in words:
by_letter[word[0]].append(word)

print(by_letter)

> {'a': ['apple'], 'p': ['pear', 'peach', 'plum'], 'b': ['banana']})
  • 合併屬性list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
members = [
# Age, name
['male', 'John'],
['male', 'Jack'],
['female', 'Lily'],
['male', 'Pony'],
['female', 'Lucy'],
]

result = defaultdict(list)
for sex, name in members:
result[sex].append(name)

print(result)
> defaultdict(<class 'list'>, {'male': ['John', 'Jack', 'Pony'], 'female': ['Lily', 'Lucy']})

複雜度分析

TC: O(n)
SC: O(n)


如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels