无法将列表添加在一起 ​​- “TypeError:float' object is not subscriptable”

无法确切地找出原因,但此代码完全按预期工作,直到我尝试打印导致 test2TypeError: float' object is not subscriptable。不管我做什么样的数学运算或 test 的内容,我仍然得到同样的错误。

问题代码:

with open("InputFileData.csv") as file:
   SampleTotalHours = file.readlines();

TotalHours = []

for element in SampleTotalHours:
   hoursAsStrings = element.split(',')
   hoursAsFloats = [float(hourString) for hourString in hoursAsStrings]
   TotalHours.append(sum(hoursAsFloats))

EmployeeNumber = 4
i = 0

TotalHoursInt = []
TotalHoursInt = TotalHours

test = [11,12,13]
test2 = TotalHoursInt[1] + test[1]
print(test2[1])

内容“InputFileData.csv”:

40.1,39.7,40,38
36,36,35.5,35.8
40,41.6,40.3,40
20.4,22.8,20,20

输出:

TypeError:float' object is not subscriptable
jackybye 回答:无法将列表添加在一起 ​​- “TypeError:float' object is not subscriptable”

您的变量 test2 是浮点值而不是列表,并且您正在打印不正确的变量的第二个索引, 所以就写

print(test2)

这应该会给你正确的答案

本文链接:https://www.f2er.com/3268.html

大家都在问