python中的defaultdict(int)
声明一个默认的value=0
的字典,可以直接cnt[c] += 1
,否则就要cnt[c] = cnt.get(c, 0) + 1
代码如下:
import collections
s = '123456789101112131415'
cnt = collections.defaultdict(int)
for c in s:
cnt[c] += 1
for k in cnt:
v = cnt[k]
print(f'key = {k}, value = {v}')
程序输出为,
key = 1, value = 8
key = 2, value = 2
key = 3, value = 2
key = 4, value = 2
key = 5, value = 2
key = 6, value = 1
key = 7, value = 1
key = 8, value = 1
key = 9, value = 1
key = 0, value = 1
上述代码也可以写成,
s = '123456789101112131415'
cnt = dict()
for c in s:
cnt[c] = cnt.get(c, 0) + 1
for k in cnt:
v = cnt[k]
print(f'key = {k}, value = {v}')
程序输出为,
key = 1, value = 8
key = 2, value = 2
key = 3, value = 2
key = 4, value = 2
key = 5, value = 2
key = 6, value = 1
key = 7, value = 1
key = 8, value = 1
key = 9, value = 1
key = 0, value = 1