Python:TypeError:'float'对象不可下标 [英] Python: TypeError: 'float' object is not subscriptable

查看:42
本文介绍了Python:TypeError:'float'对象不可下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def get_data(fp):
    data = []
    for line in fp:
        line_list_ints = [int(number) for number in line.split()]
        data.append(line_list_ints)
    return data

def calculate_grades(data):
    for line in data:
        total_points = sum(line[1:6])
        grade = get_grade(total_points)
        data.insert(0,total_points)
        data.insert(1,grade)
    return data

我收到 TypeError: 'float' object is not subscriptable for line 10. 我不明白为什么在将数字附加到数据列表之前将数字转换为整数.任何人都可以帮忙吗?我说得够清楚了吗?

I am getting the TypeError: 'float' object is not subscriptable for line 10. I do not understand why as I convert the numbers into ints before I append them into the data list. Can anyone help? Am I being clear enough?

推荐答案

具体问题是因为数据中有浮动(最终)

The specific problem is because there are floats in data (eventually)

for line in data:
    total_points = sum(line[1:6])
    grade = get_grade(total_points)
    data.insert(0,total_points)
    data.insert(1,grade)

因为您将其作为等级"插入到您的列表中

Because you insert it into your list, as 'grade'

一般的问题是您在迭代列表(数据")时正在修改它,这是一个坏主意 - 您的逻辑充其量难以阅读,并且很容易永远循环.

The general problem is that you are modifying your list ('data') while you iterate over it, which is a bad idea - your logic will be hard to read at best, and easily loop forever.

这篇关于Python:TypeError:'float'对象不可下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆