我有一个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
答案 0 :(得分:0)
使用try
和except
try:
complist =[a, b, c]
totallist=[d, e, f]
percentlist = [Decimal(c) / Decimal(t) * 100 for c,t in zip(complist, totallist)]
except:
print 'divide by zero error'
修改强>
如果要将其添加到新列表中,请使用它。
newlist = []
try:
complist =[a, b, c]
totallist=[d, e, f]
percentlist = [Decimal(c) / Decimal(t) * 100 for c,t in zip(complist, totallist)]
except:
newlist.append(0)
答案 1 :(得分:0)
怎么样
percentlist = [0 if t == 0 else Decimal(c) / Decimal(t) * 100 for c,t in zip(complist, totallist)]
答案 2 :(得分:-1)
我去了https://www.REPL.IT并尝试了您的代码。一般来说,我不认为python允许ZERO划分。我尝试了你的代码并打印(0/0),然后返回错误