使用 try: except 在 for 循环中处理 DivideZeroError 的语法错误

Syntax error using try: except within a for loop to handle DivideZeroError

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

有人可以帮助我避免每当 sum_allBounds 中的一个值为零时出现的 ZeroDivideError 吗?在 for 循环中添加 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

这不是很漂亮,但你可以做到。

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

我有这个,它似乎也能用。

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