对于Bool的循环

时间:2013-08-07 20:54:38

标签: python for-loop boolean divide-by-zero

我有一个简单的循环,它被零错误卡在除法上。我正在运行一个bool来过滤掉零值分母,但由于某种原因,我使用的bool无效。有人可以帮忙吗?我使用的是python 2.6.5

以下是我的代码中的示例:

for i in range(0,len(lines)):
    line = lines[i]
    line = line.split(";")
    leansz = line[9]
    FW = line[34]
    FS = line[35]  
    print "FS: %s  %s"%(FS,type(FS))  #troubleshooting the denominator and its type
    if FS == "0":  #I have tried FS == 0 and FS == "0" to no avail
        print 'FS == "0"' #checking if bool is working
        continue  #return to top of loop if denominator is zero
    LnSzRa = float(leansz)/(float(FS)/2)  #division by zero error   

以下是返回内容的示例,然后是错误:

FS: 184
  <type 'str'>
FS: 1241
  <type 'str'>
FS: 2763
  <type 'str'>
FS: 1073
  <type 'str'>
FS: 971
  <type 'str'>
FS: 0
  <type 'str'>
Traceback (most recent call last):
  File "mpreader.py", line 50, in <module>
    LnSzRa = float(leansz)/(float(FS)/2)
ZeroDivisionError: float division

1 个答案:

答案 0 :(得分:2)

您的FS值是字符串,其中包含文件中的换行符,因此请测试字符串值:

if FS == '0\n':

或删除换行符:

如果FS.strip()=='0':

首先将FS变成浮动:

if float(FS) == 0:
拆分时

或剥离line

line = line.strip().split(';')

进一步提示:

  • 直接遍历lines;不要使用range()

    for line in lines:
        line = line.strip()
        # do something with `line`
    

    即使您仍需要索引 ,也可以使用enumerate()生成索引:

    for i, line in enumerate(lines):
        line = line.strip()
        # do something with `line` and `i`.
    
  • 您可以使用csv模块处理将数据文件拆分为行:

    import csv
    
    with open(somefile, 'rb') as inputfile:
        reader = csv.reader(inputfile, delimiter=';')
        for row in reader:
            leansz, FW, FS = map(float, (row[9], row[34], row[35]))
            if not FS: continue
            LnSzRa = leansz / (FS / 2)