gpt4 book ai didi

python - 使用 try : except within a for loop to handle DivideZeroError 时出现语法错误

转载 作者:行者123 更新时间:2023-12-01 01:23:42 26 4
gpt4 key购买 nike

遍历多个字典,我试图计算每个字典、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

关于python - 使用 try : except within a for loop to handle DivideZeroError 时出现语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53542433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com