Divide two dictionaries of float values with zero values
我的除法有问题。我用了两本字典,我得用其他的字典把它们分开。但有些值是0。我不想出错,但我想
我的两个DICT:
争议:
1 | {0: [3.75199226626618e-79], 1: [1.0384638247478166e-25], 2: [3.876104531640006e-157]} |
普洛厄姆:
1 | {0: [1.0143598477460146e-78], 1: [0.0], 2: [2.2740883119510355e-138]} |
错误的功能:
1 2 3 4 5 6 | def bayes (probspam, probham): try: lista={k: [probspam[k][0]/probham[k][0]] for k in probham} except ZeroDivisionError: k=0 return lista |
我怎样才能告诉我的系统,当
试试这个:
1 2 3 4 5 6 7 8 9 | 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 |
这是你要找的吗?
1 2 3 | 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]作为值
1 2 3 | 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 |
列表/听写理解功能强大!:)