以下是我计算支票簿交易的课程。我的问题在于elif
语句,我在其中检查row[0] == "starting"
或"ending"
。在我也将复制和粘贴的csv文件中,它会在row[0]
中明确说明这些字词在那里,但我的startAmt
和endAmt
在运行时仍然等于0
class Checkbook:
"""Checkbook class for list of check transactions"""
def __init__(self, filename):
"""initializer for Checkbook class"""
self.name = filename
self.debitList = []
self.creditList = []
self.startAmt = 0
self.endAmt = 0.0
with open(filename) as csvFile:
readCSV = csv.reader(csvFile, delimiter = ',')
for row in readCSV:
try:
if (row[2] == " debit"):
debitAmt = row[3]
self.debitList.append(debitAmt)
elif (row[2] == " credit"):
creditAmt = row[3]
self.creditList.append(creditAmt)
elif (row[0] == "starting"):
self.startAmt += row[1]
elif (row[0] == "ending"):
self.endAmt += row[1]
except IndexError:
pass
这是.csv文件:
starting, 1000
3/1/16, Valvoline, debit, 70.00
3/1/16, Panera Bread, debit, 12.59
3/4/16, ShopRite Groceries, debit, 100.69
3/5/16, Paycheck, credit, 248.39
3/10/16, Whole Paycheck Groceries, debit, 103.23
3/12/16, Fancy Restaurant, debit, 150.34
3/18/16, Burger King, debit, 8.34
3/19/16, Paycheck, credit, 248.39
3/23/16, ATM Withdrawal, debit, 40.0,
3/24/16, Whole Paycheck Groceries, debit, 248.39
3/28/16, Fancy Restaurant, debit, 112.34
ending, 651.36
如果有人知道为什么没有注册那些字符串那么请告诉我!
答案 0 :(得分:0)
首先转换为int
:
self.startAmt += int(row[1])
答案 1 :(得分:0)
您必须记住,从文件中读取的所有值都是字符串而不是数字。如果您想进行计算,则必须智能地转换值。
您还可以简化逻辑;同时通过限制try / except块中的内容来改进代码。尝试调试问题时,try块中的大型语句体会导致问题。
所以,让我们先从读者总会给你一个列表的事实开始。如果列表包含两个元素,则表示它是起始/结束余额行。否则,它是一行显示完整的交易细节。
with open(filename) as csv_file:
reader = csv.reader(filename, delimiter=',') # , is the default, so you
# can eliminate this
for row in reader:
if len(row) == 2:
balance_type, value = row
if balance_type == 'starting':
self.start_amt += float(value)
if balance_type == 'ending':
self.end_amt += float(value)
else:
if len(row) == 4:
trans_date, comment, trans_type, amount = row
if trans_type == 'debit':
self.debit_list.append(float(amount))
if trans_type == 'credit':
self.credit_list.append(float(amount))
else:
# We have some garbage data
print('Invalid data {}'.format(row))
现在我们正在做一些明确的检查,以避免在解析我们的信息时出错。
这可能看起来像一些冗余代码,但无论何时处理外部数据(如文件,用户输入,来自数据库或网络资源的信息),最好假设您将获取垃圾数据并且明确地通过检查/验证该数据。
答案 2 :(得分:0)
类文件:
import csv
class Checkbook(object):
def __init__(self, filename):
self.name =filename
self.debitList = []
self.creditList = []
self.startAmt = 0
self.endAmt = 0.0
def Parse(self):
with open(self.name) as csvFile:
readCSV = csv.reader(csvFile, delimiter = ',')
for row in readCSV:
if (len(row) > 2):
if (row[2] == " debit"):
debitAmt = row[3]
self.debitList.append(debitAmt)
#print "debitlist"self.debitList
elif (row[2] == " credit"):
creditAmt = row[3]
self.creditList.append(creditAmt)
else:
if (row[0] == "starting"):
self.startAmt += int(row[1])
elif(row[0] == "ending"):
self.endAmt += float(row[1])
return self.debitList,self.creditList,self.startAmt,self.endAmt
类文件:
驱动程序文件:
import csvread
obj=csvread.Checkbook("text.csv")
db,cl,sa,ea=obj.Parse()
print db,cl,sa,ea