2016-11-14 67 views
1

我有分裂誤差的問題。我用兩個dictionarie和我有其他字典來劃分他們。但是有些值是0 ..我不想一個錯誤但我想除以零浮點值的兩個字典值

我的兩個字典:

probspam:

{0: [3.75199226626618e-79], 1: [1.0384638247478166e-25], 2: [3.876104531640006e-157]} 

probham:

{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:由零浮動師」?

+1

LISTA = {K:[!probspam [K] [0]/probham [K] [0],如果probham [K] [0] = 0,否則,0.0]對於probham中的k} –

回答

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 

或者,如果你需要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 

列表/字典內涵是強大的! :)

0

嘗試這種情況:

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