LoginSignup
0
1

More than 3 years have passed since last update.

文字列からそれぞれの文字がいくつあるか調べる。

Posted at
1
s = 'aeqwtwegwa'
d = {}

for c in s:
    if c not in d:
        d[c] = 0
    d[c] += 1

print(d)
1の実行結果
{'a': 2, 'e': 2, 'q': 1, 'w': 3, 't': 1, 'g': 1}
2
s = 'aefqwdqfqwe'
d = {}

for c in s:
    d.setdefault(c, 0)
    d[c] += 1

print(d)
2の実行結果
{'a': 1, 'e': 2, 'f': 2, 'q': 3, 'w': 2, 'd': 1}

標準ライブラリからdefaultdictを読み込んで書くと、

3
from collections import defaultdict

s = 'raegiowejgohg'
d = defaultdict(int)

for c in s:
    d[c] += 1

print(d)
print(d['g'])
3の実行結果
defaultdict(<class 'int'>, {'r': 1, 'a': 1, 'e': 2, 'g': 3, 'i': 1, 'o': 2, 'w': 1, 'j': 1, 'h': 1})
3
0
1
1

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
1