回答編集履歴

3

修正

2020/04/07 05:59

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -102,7 +102,7 @@
102
102
 
103
103
  else:
104
104
 
105
- words_dic[word] = 0
105
+ words_dic[word] = 1
106
106
 
107
107
  ```
108
108
 

2

追記

2020/04/07 05:58

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -83,3 +83,63 @@
83
83
  words_dic[word] = new_cnt # 更新した個数を登録
84
84
 
85
85
  ```
86
+
87
+
88
+
89
+ おまけ: カウント処理いろいろ
90
+
91
+ ---
92
+
93
+ **明示的に分岐する方法**
94
+
95
+ ```Python
96
+
97
+ for word in words:
98
+
99
+ if word in words_dic:
100
+
101
+ words_dic[word] += 1
102
+
103
+ else:
104
+
105
+ words_dic[word] = 0
106
+
107
+ ```
108
+
109
+
110
+
111
+ **defaultdictを利用する方法**
112
+
113
+ ```Python
114
+
115
+ import collections
116
+
117
+
118
+
119
+ words_dic = collections.defaultdict(int)
120
+
121
+ ...
122
+
123
+
124
+
125
+ for word in words:
126
+
127
+ words_dic[word] += 1
128
+
129
+ ```
130
+
131
+
132
+
133
+ **Counterを利用する方法**
134
+
135
+ ```Python
136
+
137
+ import collections
138
+
139
+
140
+
141
+ ...
142
+
143
+ words_dic = collections.Counter(words)
144
+
145
+ ```

1

追記

2020/04/07 05:56

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -65,3 +65,21 @@
65
65
 
66
66
 
67
67
  カウントアップ処理にはぴったりのメソッドですね。
68
+
69
+
70
+
71
+ ---
72
+
73
+ ともすれば次のように冗長に書いた方が、**今は**分かり易いかもしれません。
74
+
75
+ ```Python
76
+
77
+ for word in words:
78
+
79
+ now_cnt = words_dic.get(word, 0) # 現状の個数を獲得 (登録されていない場合は0)
80
+
81
+ new_cnt = now_cnt + 1 # 個数を更新
82
+
83
+ words_dic[word] = new_cnt # 更新した個数を登録
84
+
85
+ ```