【发布时间】:2020-11-12 00:52:49
【问题描述】:
如果作为字典键的 all_keys 变量中不存在 list_goods[i] 项,我应该捕获异常并将后跟值“none”的项添加到新的字典变量中。但是我的代码不起作用。如果有人能指出我正确的方向,谢谢!P.s 我不应该在这个作业中使用 If else。
main方法中的列表和字典
dict_q2 = {"vinegar": [120.0, 100], "ketchup": [950, 1000],"apples": [850,1100],"oranges": [1050, 0]
}
list_q2 = ["ketchup","oranges","pear"]
上面的list和dict的函数
def compute_unit_prices(dict_goods, list_goods):
#dict variable with name of good as key and unit prices as values.
return_dict = {}
all_keys = dict_goods.keys()
i =0
#Try block
try:
while (list_goods[i] in all_keys):
goods_name = list_goods[i]
storage = dict_goods[goods_name]
results = storage[0] / storage[1]
return_dict.update({goods_name:results})
i = i+1
except KeyError as e:
return_dict.update({goods_name:"none"})
# If zeroDivisionError is encountered, this block of code is used
except ZeroDivisionError as e:
results = -1
return_dict.update({goods_name:results})
# This block of code works if errors other than the above two occurs
except:
return_dict = {}
finally:
print(return_dict)
【问题讨论】:
-
你为什么“应该抛出异常”?如果
list_goods[i]不在all_keys中,为什么不能简单地采取补救措施? -
这里有很多问题。首先,如果此处抛出异常,
goods_name变量可能未定义:while (list_goods[i] in all_keys):。此外,如果抛出异常,您不会更改i的值,因此您将一遍又一遍地保持相同的值。最后,except KeyError as e- 这里的变量e没有用于任何事情,为什么有它呢? -
顺便说一句,如果您说出问题所在,它可能会有所帮助。令人惊讶的是您的代码,即使它在我的电脑上运行不正确。
{'ketchup': 0.95, 'oranges': -1} -
面临的问题是,你获得的输出是答案的一部分。但是我应该有一个额外的“梨”:没有。因此对于不在 dict_q2 中的梨,其值将自动设置为无。我曾尝试使用关键错误异常但无济于事,因为我不应该使用 If-else 语句。
-
我明白了。检查我的答案。
标签: python