在脚本中通过除法实例忽略零

Mat*_*att -1 python divide-by-zero python-2.7

有没有办法忽略列表中的值,在迭代脚本中创建除零而不是删除这些问题值?

我正在考虑如果

if(x==0):
 break
elif(x!=0):
 continue
Run Code Online (Sandbox Code Playgroud)

其中非零值通过脚本继续.

eng*_*ree 6

您可以使用列表推导来获得更高效的代码,

from __future__ import division
num = [1,2,3,4,5,6,3,31,1,0,120,0,0]
divisor = 10
print [divisor/x for x in num if x != 0]
Run Code Online (Sandbox Code Playgroud)

输出:

[10.0, 5.0, 3.3333333333333335, 2.5, 2.0, 1.6666666666666667, 3.3333333333333335, 0.3225806451612903, 10.0, 0.08333333333333333]
Run Code Online (Sandbox Code Playgroud)