将两个浮点值字典除以零值
Divide two dictionaries of float values with zero values
我有除法错误的问题。我使用两个字典,我必须将它们除以其他字典。但有些值为 0。我不想出错,但我想要
我的两个字典:
问题垃圾邮件:
{0: [3.75199226626618e-79], 1: [1.0384638247478166e-25], 2: [3.876104531640006e-157]}
问题:
{0: [1.0143598477460146e-78], 1: [0.0], 2: [2.2740883119510355e-138]}
错误函数:
def bayes (probspam, probham):
try:
lista={k: [probspam[k][0]/probham[k][0]] for k in probham}
except ZeroDivisionError:
k=0
return lista
我怎么能告诉我的系统,当probham[k]=0
时,它应该将除法结果赋值为0而不是给我:"ZeroDivisionError: float division by zero"?
是您要找的吗?
def bayes (probspam, probham):
lista={k: [probspam[k][0]/probham[k][0] if probham[k][0] !=0 else .0] for k in probham}
return lista
或者,如果您需要 0.0 而不是 [0.0] 作为值
def bayes (probspam, probham):
lista={k: [probspam[k][0]/probham[k][0]] if probham[k][0] !=0 else .0 for k in probham}
return lista
List/dict感悟强大! :)
试试这个:
def bayes(probspam, probham):
lista = {}
for k in probham:
if probham[k][0] != 0:
lista[k] = [probspam[k][0]/probham[k][0]]
else:
lista[k] = [0.0]
return lista
我有除法错误的问题。我使用两个字典,我必须将它们除以其他字典。但有些值为 0。我不想出错,但我想要
我的两个字典:
问题垃圾邮件:
{0: [3.75199226626618e-79], 1: [1.0384638247478166e-25], 2: [3.876104531640006e-157]}
问题:
{0: [1.0143598477460146e-78], 1: [0.0], 2: [2.2740883119510355e-138]}
错误函数:
def bayes (probspam, probham):
try:
lista={k: [probspam[k][0]/probham[k][0]] for k in probham}
except ZeroDivisionError:
k=0
return lista
我怎么能告诉我的系统,当probham[k]=0
时,它应该将除法结果赋值为0而不是给我:"ZeroDivisionError: float division by zero"?
是您要找的吗?
def bayes (probspam, probham):
lista={k: [probspam[k][0]/probham[k][0] if probham[k][0] !=0 else .0] for k in probham}
return lista
或者,如果您需要 0.0 而不是 [0.0] 作为值
def bayes (probspam, probham):
lista={k: [probspam[k][0]/probham[k][0]] if probham[k][0] !=0 else .0 for k in probham}
return lista
List/dict感悟强大! :)
试试这个:
def bayes(probspam, probham):
lista = {}
for k in probham:
if probham[k][0] != 0:
lista[k] = [probspam[k][0]/probham[k][0]]
else:
lista[k] = [0.0]
return lista