我已经正确学习python几周了,但我找不到一种方法来继续我目前必须获得输入文件中的每一行,以date=total格式打印输出行。因此,日期之后的所有内容都被添加到总数中。
期望的结果是:
2006-04-10 = 1399.46
2006-04-11 = 2822.36
2006-04-12 = 2803.81
2006-04-13 = 1622.71
2006-04-14 = 3119.60
2006-04-15 = 2256.14
2006-04-16 = 3120.05
2006-04-20 = 1488.00
来自包含以下值的data60.txt:
2006-04-10,836.2,563.263
2006-04-11,462.06,1694.3,666.0
2006-04-12,1318.19,1485.62
2006-04-13,49.714,304.0,1269.0
2006-04-14,1360.0,1731.0,28.6
2006-04-15,998.879,890.264,367.0
2006-04-16,757.4,1501.05,861.6
2006-04-20,1218.0,270.0
这就是我目前拥有的:
def print_daily_totals(filename):
"""For each line in the input file, print an output line
in the format date = total
"""
infile = open(filename)
lines = infile.readline()
pieces = filename.split(',')
date = pieces[0]
total = float(sum(pieces[1::]))
print("{0} = {1}".format(date, total))
lines = infile.readline()
infile.close()
print_daily_totals('data60.txt')
我想我对分手感到困惑了。我们将非常感谢您的帮助!
首先,您没有迭代所有的文件行
其他事情您正在转换错误的float(sum(pieces[1::]))
。pieces
是字符串列表。您无法对字符串求和,因此需要在使用sum([float(i) for i in pieces[1:]])
求和之前将它们转换为浮点值
def print_daily_totals(filename):
"""For each line in the input file, print an output line
in the format date = total
"""
with open(filename, 'r') as f:
for line in f:
pieces = line.split(',')
date = pieces[0]
total = sum([float(i) for i in pieces[1:]])
print("{0} = {1:.2f}".format(date, total))
print_daily_totals('data60.txt')
输出:
2006-04-10 = 1399.46
2006-04-11 = 2822.36
2006-04-12 = 2803.81
2006-04-13 = 1622.71
2006-04-14 = 3119.60
2006-04-15 = 2256.14
2006-04-16 = 3120.05
2006-04-20 = 1488.00
编辑
如果你不知道与声明和列表理解
def print_daily_totals(filename):
"""For each line in the input file, print an output line
in the format date = total
"""
infile = open(filename)
lines = infile.readlines()
for line in lines:
pieces = line.split(',')
date = pieces[0]
total = 0
for i in pieces[1:]:
total += float(i)
print("{0} = {1:.2f}".format(date, total))
infile.close()
print_daily_totals('filetest.csv')
我认为应该是:
total = sum(float(i) for i in pieces[1:])