我经常发现自己使用dict来计算某些东西的出现次数,我想知道是否有一种方法可以在不使用异常的情况下更顺畅.
count_dict = {}
for file in files:
############
#parse file#
############
for line in lines:
tokens = line.split()
if "something" in tokens:
try:
count_dict[tokens[0]] += 1
except KeyError:
count_dict[tokens[0]] = 1
Run Code Online (Sandbox Code Playgroud)
Python有一个专门用于此的类:collections.Counter.
count_dict = Counter(str.split())
Run Code Online (Sandbox Code Playgroud)