面白いコードですね :)
やはり味噌はこの行でしょうか
python
1 count[character]=count[character] +1
結論だけ申し上げますと、
「該当した文字だった場合、そのcount辞書型の該当の文字キーに1加算している」
という処理になりますね。
TL; DR(長ったらしい解説のため、読み飛ばし可能です)
その前に、まずはこのコードの実行結果を見たほうがよいでしょうか。
{'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l': 3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}
「そりゃそうだよ! そういう結果になったよ!(半ギレ)」
と思われるかもしれませんね。
じゃあ、
python
1 count[character]=count[character] +1
では何が行われているか、具体的に文字を入れながら見ていきましょう。
実際に文字を一文字ずつ入れてみる
"I" の動作
python
1message='It was a bright cold day in April, and the clocks were striking thirteen.'
2# now! ^
3
4 count["I"]=count["I"] +1
ご覧の通り、 count 辞書型の I というキーに、数値を1つ足してるんですね。
では、実際の数値はどうなっているでしょうか。
python
1message='It was a bright cold day in April, and the clocks were striking thirteen.'
2# now! ^
3
4# 0 +1
5 count["I"]=count["I"] +1
ということが行われております。もちろん count 辞書の I に 数値 0 が入っているのは、
python
1count.setdefault(character , 0)
の行で、「 count 配列に character のキー(文字)がなかったら、 0 をセットして」
と処理しているからです。
"t" の動作
では、 "t" はどうなってるでしょう?
python
1message='It was a bright cold day in April, and the clocks were striking thirteen.'
2# now! ^
3
4# 0 +1
5 count["t"]=count["t"] +1
これも1加算されます。
続けて" "の文字
python
1message='It was a bright cold day in April, and the clocks were striking thirteen.'
2# now! ^
3
4# 0 +1
5 count[" "]=count[" "] +1
これも、まずは1加算されます。
これ以上書くときっとうんざりしてしまうと思うので、このへんで。
更に同じ文字があれば、もちろん以下のようになります。
python
1message='It was a bright cold day in April, and the clocks were striking thirteen.'
2# now! ^
3
4# 1 +1
5 count["a"]=count["a"] +1
6# count["a"]は2になる
という事を、一文字ずつ処理しています。
まとめ
python
1for character in message: # messageの中を一文字ずつcharacterに入れる
2 count.setdefault(character , 0) # count辞書にcharacterのキーがない場合、0を代入
3 count[character]=count[character] +1 # ここに来るときには絶対にキーがあるので、辞書の要素に1加算
という具合です。
長ったらしい説明を最後まで読んでくださり、ありがとうございます。
2018/11/02 04:22
2018/11/02 06:46
2018/11/02 07:08