【问题标题】:How to avoid division by zero error, when performing calculations on parsed xml data对解析的 xml 数据执行计算时如何避免除以零错误
【发布时间】:2013-06-05 02:32:38
【问题描述】:

请善待您的答案,我已经编码了 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.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 %

现在这个 xmlload 的结果表明只有三个用户要解析,但是有第四个用户的数据会读取

number of selections =  0
number of winners =  0
Strike rate =  0

出于我的目的,没有必要为那些没有跟踪记录的人提取用户统计信息,我如何使代码跳过具有 0 个选择的用户,或者至少使代码除以零错误不会影响代码循环运行的能力?

亲切的问候!

【问题讨论】:

    标签: python loops python-2.7 division divide-by-zero


    【解决方案1】:

    找到 0 时只需使用 continue

    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;
    

    【讨论】:

    • 感谢 Ashwin 的回答,我将代码调整为我认为您必须要表达的意思(用 user_numberofselections 替换 user_numberofwinners)但是代码仍然返回 ZeroDivisionError: float division by zero 我仔细检查了这是说计算导致通过将它们注释掉并仅打印选择数量和获奖者数量来解决错误:number of selections = 112.0 number of winners = 21.0 number of selections = 146.0 number of winners = 21.0 number of selections = 163.0 number of winners = 55.0 number of selections = 0.0 number of winners = 0.0
    • 修正了我的答案。必须使用== 而不是isfloat 进行比较
    • 非常感谢 Ashwin,我知道它的基本编码,但每次我得到这样的新答案时,它都会增加我的技能! :)
    • 任何时候你测试浮点数的相等性,你都可能犯了一个错误。浮点数的行为不像您预期​​的那样。你认为这是什么结果?对还是错?:python -c "x = 111111111111111111111; print((x + 0.0) == x)"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 2019-12-18
    • 2014-09-25
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多