我有以下功能:
def calculate(blob, count_per_data):
return geometric_mean( [score_per_count[ count_per_data[data] ] for data in combinations(blob)] )
我的代码的问题是,如果在 count_per_data
中找不到 data
,我会得到一个异常。相反,我希望 count_per_data["unknown"]
的计算结果为 0,即 "unknown"
的计数为 0。
反过来,值 0 存在于 score_per_count
中并且不等于 0。换句话说,与 0 相关联的分数本身不是 0。
您会建议我如何修复上述代码以实现我的目标?
最佳答案
如果你想确保 data
存在于 count_per_data
中并且 count_per_data
的值存在于 score_per_count
,你可以像这样使用列表理解作为过滤器
return geometric_mean([score_per_count[count_per_data[data]] for data in combinations(blob) if data in count_per_data and count_per_data[data] in score_per_count])
更具可读性的版本,
return geometric_mean([score_per_count[count_per_data[data]]
for data in combinations(blob)
if data in count_per_data and count_per_data[data] in score_per_count])
但是,如果您想在字典中找不到键时使用默认值,那么您可以使用dict.get
。引自 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.
你可以像这样使用它
count_per_data.get(data, 0)
如果 count_per_data
中没有找到 data
,将使用 0
代替。
关于python - 列表理解中的 KeyError 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21328668/