python - 为什么我会得到 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
,我认为字典赋予它``
值并且不能转换为0
by float()
。但似乎这不是问题,但老实说我现在不知道,所以这就是我在这里问的原因。
完整的错误:
Growth = -float(x['MID'])/float(x['MID'])
ZeroDivisionError: float division by zero
任何关于此的提示都非常有价值。
解决方案
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
陈述做同样的事情
推荐阅读
- docker - Docker 镜像无法连接到公共 IP 地址
- r - Stargazer float.env = "sidewaystable" 导致表格在文档中
- java - 如何在java lambda函数中配置sqs的属性?
- azure - 将资源 uri 添加到缩放对象
- tcl - 在其他文件中自动加载 Itcl 类方法
- angular - 如何从输入装饰器跟踪对象值?将数据从父组件传递到子组件?
- r - 为什么 plotly 条形图在 R 中不按顺序使用我指定的颜色,我如何强制它按顺序使用我的颜色?
- python - 保存到 Excel 工作表时无法将 String 转换为 int
- flutter - Flutter GridView 图像放大缩小
- python - 导入python包时GSL未定义符号