在下面的代码中,什么更高效/更“Pythonic”?使用 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 选项,但我不知道为什么。