gpt4 book ai didi

Python:尝试除了 KeyError 与 if has_key()

转载 作者:IT老高 更新时间:2023-10-28 21:06:50 25 4
gpt4 key购买 nike

在下面的代码中,什么更高效/更“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 选项,但我不确定为什么。

最佳答案

使用 dict.get() :

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

换句话说d.get('x', c)相当于 d['x'] if 'x' in d else c .

示例:

In [24]: d = {'a':1, 'b':2}

In [27]: d['d'] = d.get('d', 0) + 1 # 0 is the default value

In [28]: d
Out[28]: {'a': 1, 'b': 2, 'd': 1}

In [29]: d['d'] = d.get('d', 0) + 1

In [30]: d
Out[30]: {'a': 1, 'b': 2, 'd': 2}

关于Python:尝试除了 KeyError 与 if has_key(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com