AEA*_*AEA 0 python loops division divide-by-zero python-2.7
请善待您的答案我现在已经编码了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()
Run Code Online (Sandbox Code Playgroud)
此代码与其余代码返回:
number of selections = 112.0
number of winners = 21.0
Strike rate = 18.75 %
number of selections = 146.0
number of winners = 21.0
Strike rate = 14.3835616438 %
number of selections = 163.0
number of winners = 55.0
Strike rate = 33.7423312883 %
Run Code Online (Sandbox Code Playgroud)
现在这个xmlload的结果表明只有三个用户要解析,但是有第四个数据会被读取
number of selections = 0
number of winners = 0
Strike rate = 0
Run Code Online (Sandbox Code Playgroud)
为了我的目的,没有必要为那些没有跟踪记录的人提供用户统计信息,我如何使代码跳过0选择的用户或至少使其成为零除错误不影响能力要在循环中运行的代码?
亲切的问候!
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;
Run Code Online (Sandbox Code Playgroud)