gpt4 book ai didi

python - 类型错误 : 'float' object has no attribute '__getitem__'

转载 作者:行者123 更新时间:2023-11-30 23:36:49 25 4
gpt4 key购买 nike

此代码是将 csv 文件读入几个列表的初步尝试。我收到下面的错误,并且我不明白为什么没有返回 float 。感谢您的帮助!

 File "main.py", line 32, in <module>
LR.openfile('djia_temp.csv')
File "main.py", line 9, in openfile
self.xs = self.tempDiff(dataAvgandtemp)
File "main.py", line 18, in tempDiff
tdArray.append([vector[0]-vector[1]])
TypeError: 'float' object has no attribute '__getitem__'

代码:

from processFile import processFile
import numpy as np

class processFile:

@staticmethod
def wholeFile(f):
fileArray = []
for line in f:
fileArray.append(line.strip())
return fileArray

@staticmethod
def liner(rows, columns, delimiter):
vectors = []
for row in rows:
vector = []
tok = row.split(delimiter)
for num in columns:
vectors.append(float(tok[num]))
return vectors

class linRegmain:
def openfile(self, file):
f = open(file)
a = processFile.wholeFile(f)[1:]
dataAvgandtemp = processFile.liner(a, [2,3], ";")
self.xs = self.tempDiff(dataAvgandtemp)
self.ys = processFile.liner(a,[1], ";")
print self.xs
print self.ys


def tempDiff(self, vectors):
tdArray = []
for vector in vectors:
tdArray.append([vector[0]-vector[1]])
return tdArray

if __name__ == '__main__':
LR = linRegmain()
LR.openfile('djia_temp.csv')

最佳答案

liner() 声称返回向量列表。它不是。您正在创建一个 float 列表:

vectors.append(float(tok[num]))

因此,当您使用结果调用 tempDiff() 时,vector 是一个 float,因此 vector[0] 抛出异常。

我认为这就是它应该做的:将每个浮点添加到当前向量,然后将向量添加到结果:

@staticmethod
def liner(rows, columns, delimiter):
vectors = []
for row in rows:
vector = []
tok = row.split(delimiter)
for num in columns:
vector.append(float(tok[num])) # append to vector, not vectors
vectors.append(vector) # then append the vector to the result
return vectors

关于python - 类型错误 : 'float' object has no attribute '__getitem__' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16157694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com