试图从行的末尾获取值并将它们添加到一起

时间:2014-03-17 02:38:08

标签: python function slice

我试图从所有日志中获得总成本(每行末尾的值)但我不断得到错误“切片索引必须是整数或无或者索引方法 “每行在值之前都有不同的长度。这段代码还没有增加成本,但我确定我已经到了。

日志记录输入功能(rec.dat): *此日志将是输入函数的记录

@ 2014 2 14 00:03:01马特“登录”0.01

@ 2014 2 14 02:06:12玛丽“登录”0.01

@ 2014 2 14 17:12:05玛丽“cd~ / cs150 / projects”0.01

功能:

该功能的目标是增加所有操作的成本(在这种情况下,成本应该总计为.03)

def cost(rec):
    s = Scanner(rec)
    cost = 0
    line = s.readline()
    for i in range(0, len(rec), 1):
        info = len(line) - 3
        n = float(info)
        price = line[n:0]
        cost += price
        line = s.readline()
    s.close()
    return cost

1 个答案:

答案 0 :(得分:1)

您不能使用float进行切片,替换:

n = float(info)
price = line[n:0]

使用:

price = line[info:0]

您根本不需要n变量。