django 使用try时出现语法错误:除了在for循环中处理DivideZeroError

g6ll5ycj  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(154)

在多个dict中迭代,我试图计算每个dict中值的百分比,sum_allBlocks和sum_allBounds。然后将这些数据作为列表添加到新的dict中。
有人可以帮助我避免我的ZeroDivideError,我得到每当sum_allBounds中的值之一是零?添加try时出现语法错误:除了:在for循环中。

#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
7cwmlq89

7cwmlq891#

虽然不好看,但你可以做到。

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
tv6aics1

tv6aics12#

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

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

相关问题