简体   繁体   English

Python:TypeError:“ float”对象不可下标

[英]Python: TypeError: 'float' object is not subscriptable

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

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. 我收到TypeError:第10行的“ float”对象无法下标。我不明白为什么在将数字附加到数据列表之前将数字转换为int的原因。 Can anyone help? 有人可以帮忙吗? Am I being clear enough? 我足够清楚吗?

The issue is that you're modifying the data list while you're iterating over it, using data.insert in calculate_grades . 问题是,你正在修改的data列表,而你遍历它,使用data.insertcalculate_grades This leads to the second iteration of the loop to see the grade value from the previous iteration as line , rather than the list of integers it is expecting. 这导致循环的第二次迭代将上一次迭代的grade值视为line ,而不是它期望的整数列表。

I don't entirely understand what you're trying to do, so I can't suggest a solution directly. 我不完全了解您要做什么,所以我不能直接建议解决方案。 Perhaps you should make a separate list for the output, or modify line in place, rather than inserting a new item into data . 也许您应该为输出创建一个单独的列表,或者在适当位置修改line ,而不是在data插入新项目。

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. 普遍的问题是,您在遍历列表时会修改列表(“数据”),这是一个坏主意-您的逻辑充其量将很难阅读,并且很容易永久循环。

嗯,问题出在第10 line[1:6]的部分line[1:6] 。可变line是浮点数,因此您不能使用子列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM