使用try:的语法错误,但用于处理DivideZeroError

时间:2018-11-29 15:31:15

标签: python django for-loop next

我遍历多个字典,尝试从每个字典,sum_allBlocks和sum_allBounds计算值的百分比。然后,我将这些数据作为列表添加到新字典中。

有人可以帮助我避免sum_allBounds中的值之一为零时出现的ZeroDivideError吗?在try循环中添加try:except:时出现语法错误。

#Get Block% by Stand from allstands, add to daily_details as percent_allBlocks

def get_flight_details(stand_data):
    for _key, allstands in stand_data.items():
        daily_details = {}
        divide_allBlocks = ["{0:3.1f}%".format(a / b * 100) for a, b in zip(sum_allBlocks, sum_allBounds)]
        daily_details['percent_allBlocks'] = divide_allBlocks

2 个答案:

答案 0 :(得分:2)

虽然不漂亮,但是您可以做到。

def get_flight_details(stand_data):
    for _key, allstands in stand_data.items():
        daily_details = {}
        divide_allBlocks = ["{0:3.1f}%".format(a/b*100 if b!=0 else <PUT A DEFAULT VALUE HERE>) for a, b in zip(sum_allBlocks, sum_allBounds)]
        daily_details['percent_allBlocks'] = divide_allBlocks

答案 1 :(得分:0)

我有这个,它似乎也可以工作。

try:
    divide_allBlocks = ["{0:3.1f}%".format(a / b * 100) for a, b in zip(sum_allBlocks, sum_allBounds)]
except ZeroDivisionError:
    divide_allBlocks = [0.0 for a, b in zip(sum_allBlocks, sum_allBounds)]
daily_details['percent_allBlocks'] = divide_allBlocks