如何将一个数除以一组包含0的数?

How to divide a number a set of numbers that contains 0?

我正在尝试为变量分配其他两个除以结果的值,但是,其中一个除以 0。

我的变量如下 total_cost=[312198.0,230400.0,374345.0,367979.0,415502.0) alpha=[0.8181818181818182,0.6666666666666666,0.3076923076923077,0.6153846153846154,0.0]

我想要的输出是 cost_feasibility_efficiency=[381575.33,345949.94,1216621.24,597965.87,0]

我当前的密码是

cost_feasibility_efficiency=[0.0,0.0,0.0,0.0,0.0]
for i in range(0,len(alpha)):
    cost_feasibility_efficiency[i]=total_cost[i]/alpha[i]
    
print(cost_feasibility_efficiency) 

我收到的错误是“浮点数除以零”

你可以使用try/except来捕获异常:

cost_feasibility_efficiency=[0.0,0.0,0.0,0.0,0.0]
for i in range(0,len(alpha)):
    try:
        cost_feasibility_efficiency[i] = total_cost[i] / alpha[i]
    except ZeroDivisionError:
        cost_feasibility_efficiency[i] = 0.0

print(cost_feasibility_efficiency)

由于不允许除以零,我们可以在除法之前确保我们的分母 alpha[i] 不为零:

    cost_feasibility_efficiency=[0.0,0.0,0.0,0.0,0.0]
    for i in range(0,len(alpha)):
        if alpha[i] == 0:
            cost_feasibility_efficiency[i] = 0.0
        else:
            cost_feasibility_efficiency[i]=total_cost[i]/alpha[i]

    print(cost_feasibility_efficiency) 

您可以选择如果我们 运行 被零除会发生什么。在上面的例子中,它只是将结果设置为 0.0.