首页 > 解决方案 > 为什么我会得到 ZeroDivisionError?

问题描述

我正在尝试编写读取 .csv 文件的 python 程序。我在输入文件中有 4 个列/字段,我只想在输出中有 2 个,其中一个是新的。

这是我正在使用的输入:

MID,REP,NAME,NEPTUN
0,,"people's front of judea",GM6MRT
17,,Steve Jobs,NC3J0K
,0,Brian,RQQCFE
19,9,Pontius Pilate,BQ6IAJ
1,,N. Jesus,QDMXVF
18,,Bill Gates,D1CXLO
0,,"knights who say NI",CZN5JA
 ,1,"Robin, the brave",BWQ5AU
17,19,"Gelehed, the pure",BY9B8G

那么输出应该是这样的(不是完整的输出):

NEPTUN,GROWTH
BQ6IAJ,-0.5263157894736842
BWQ5AU,inf
BY9B8G,0.11764705882352941
RQQCFE,0

调用的新字段GROWTH由 (REP-MID)/MID 计算。

所以,我使用两个列表来做到这一点:

import csv

L = []
s =[]
with open('input.csv', 'rb') as R:
    reader = csv.DictReader(R)
    for x in reader:
        if  x['MID'] != '' or '0' and x['REP'] == '':
            Growth = -float(x['MID'])/float(x['MID'])
            L.append(x)
            s.append(Growth)
        elif  x['MID'] != '' or '0':
            Growth = (float(x['REP']))-float(x['MID'])/float(x['MID'])
            L.append(x)
            s.append(Growth)
        elif x['MID'] and x['REP'] == '' or '0' :
            Growth = 0
            L.append(x)
            s.append(Growth) 
        else:
            Growth = float("inf")
            L.append(x)
            s.append(Growth) 
    for i in range(len(s)):
        L[i]['GROWTH'] = i
R.close()
with open('output.csv', 'wb') as output:
    fields = ['NEPTUN', 'GROWTH']
    writer = csv.DictWriter(output, fieldnames=fields, extrasaction='ignore')
    writer.writeheader()
    writer.writerows(L)
output.close()   

现在,我什至不确定代码是否正确或是否符合我的目标,因为我ZeroDivisionError: float division by zero在第一个if条件下被卡住了,我尝试了很多方法来避免它,但我得到了同样的错误。

我认为问题在于,当字段没有值时MID,我认为字典赋予它``值并且不能转换为0by float()。但似乎这不是问题,但老实说我现在不知道,所以这就是我在这里问的原因。

完整的错误:

Growth = -float(x['MID'])/float(x['MID'])

ZeroDivisionError: float division by zero

任何关于此的提示都非常有价值。

标签: pythonpython-2.7csvdictionary

解决方案


if x['MID'] != '' or '0' and x['REP'] == ''

这并不意味着你认为它意味着什么。它被解释为

if ((x['Mid'] != '') or ('0')) and (x['REP'] == '')

缩短为

if True and x['REP'] == ''

这反过来变成

if x['REP'] == ''

你的意思是

if x['Mid'] not in ('', '0') and (x['REP'] == ''):

你需要对你的其他if陈述做同样的事情


推荐阅读