为了账号安全,请及时绑定邮箱和手机立即绑定

对已解析的xml数据执行计算时,如何避免零错误除法

对已解析的xml数据执行计算时,如何避免零错误除法

达令说 2021-03-16 09:13:59
请回答我,我已经编码了10天了。我在执行代码中的循环时遇到麻烦,但是我可以肯定的是,这是因为我得到了回溯。我使用以下代码解析从url获得的xml文件:pattern4 = re.compile('title=\'Naps posted: (.*) Winners:')pattern5 = re.compile('Winners: (.*)\'><img src=')for row in xmlload1['rows']:    cell = row["cell"]##### defining the Keys (key is the area from which data is pulled in the XML) for use   in the pattern finding/regex    user_delimiter = cell['username']    selection_delimiter = cell['race_horse']##### the use of the float here is to make sure the result of the strike rate calculations returns as a decimal, otherwise python 2 rounds to the nearest integer!     user_numberofselections = float(re.findall(pattern4, user_delimiter)[0])    user_numberofwinners = float(re.findall(pattern5, user_delimiter)[0])    strikeratecalc1 = user_numberofwinners/user_numberofselections    strikeratecalc2 = strikeratecalc1*100##### Printing the results of the code at hand    print "number of selections = ",user_numberofselections    print "number of winners = ",user_numberofwinners    print "Strike rate = ",strikeratecalc2,"%"    print ""getData()此代码与其余代码一起返回:number of selections =  112.0number of winners =  21.0Strike rate =  18.75 %number of selections =  146.0number of winners =  21.0Strike rate =  14.3835616438 %number of selections =  163.0number of winners =  55.0Strike rate =  33.7423312883 %现在,此xmlload的结果表明,只有三个用户要解析,但是有第4个whos数据会读取number of selections =  0number of winners =  0Strike rate =  0出于我的目的,对于没有跟踪记录的用户,没有必要拉入用户统计信息,我该如何使代码跳过选择0的用户,或者至少使其不被零除的错误不会影响要在循环中运行的代码?
查看完整描述

1 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

continue找到0时仅使用a 。


user_numberofwinners = float(re.findall(pattern5, user_delimiter)[0])


# if the number of winners is 0, go to the next row to avoid division by 0

if user_numberofwinners == 0.0 : continue;


查看完整回答
反对 回复 2021-03-30
  • 1 回答
  • 0 关注
  • 152 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信