在下面的代码中,哪种方法更高效/更符合Python风格?使用 try-catch 子句还是 if-else 子句?
fname = 'AdobeARM.log'
letters = {}
with open(fname,'r') as f:
for line in f:
for c in line:
try:
letters[c] += 1
except KeyError:
letters[c] = 1
print letters
VS.
:这是一个常见的缩写,表示“对比”或“对抗”。fname = 'AdobeARM.log'
letters = {}
with open(fname,'r') as f:
for line in f:
for c in line:
if letters.has_key(c):
letters[c] += 1
else:
letters[c] = 1
print letters
我倾向于使用try catch选项,但我不确定为什么。