gpt4 book ai didi

python - 当出现 0/0 时,如何避免 Decimal 函数失败?

转载 作者:太空宇宙 更新时间:2023-11-04 04:33:19 25 4
gpt4 key购买 nike

我有一个 Python 2.7 脚本,它使用两个列表并将数字彼此分开,然后创建一个包含结果的新列表,它工作正常,但每当脚本必须除 0/0 时,它就会在下面的行中出错,这种情况有时会发生,具体取决于我当前服务器的状态。有什么办法可以避免这种情况吗?

complist =[a, b, c]
totallist=[d, e, f]

percentlist = [Decimal(c) / Decimal(t) * 100 for c,t in zip(complist, totallist)]

我收到错误:

    MacBook-Pro-3$ python dailyReport.py 
Traceback (most recent call last):
File "dailyReport.py", line 67, in <module>
percentlist = [Decimal(l) / Decimal(t) * 100 for l,t in zip(complist, totallist)]
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 1321, in __truediv__
return context._raise_error(DivisionUndefined, '0 / 0')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 3873, in _raise_error
raise error(explanation)
decimal.InvalidOperation: 0 / 0

最佳答案

怎么样

percentlist = [0 if t == 0 else Decimal(c) / Decimal(t) * 100 for c,t in zip(complist, totallist)]

关于python - 当出现 0/0 时,如何避免 Decimal 函数失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43668301/

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