TypeError不支持的操作数

时间:2016-04-12 05:58:55

标签: python csv typeerror

我之前得到了帮助并得到了我的代码,但不幸的是我得到了语法错误,我花了一些时间试图解决它,但我无法解决它。任何人都可以指出我做错了什么。 而且我已经对它进行了一些编辑,但现在我已经知道如何修复它了。 第24行的错误

TypeError:/:' int'不支持的操作数类型和'列出'

import csv
#turn csv files into a list of lists
with open('train.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=',')
     csv_data = list(reader)

i_list = []
for row in csv_data:
    if (row and int(row[13]) > 0):
        i_list.append(int(row[13]))
H_list = []
for row in csv_data:
    if (row and int(row[13]) <= 0):
        H_list.append(int(row[13]))
except IndexError:
        print("could not find the heart diseases status for the row" + str(row))
Icount = len(i_list)
IPavg = sum(i_list)/len(i_list)
file = open("train.csv")
numline = len(file.readlines())
Hcount = len(H_list)
HPavg = sum(H_list)/len(H_list)


print(numline)
print("Total amount of healthy patients " + str(Icount))
print("Total amount of ill patients " + str(Hcount))
print("Averages of healthy patients " + str(HPavg))
print("Averages of ill patients " + str(IPavg))

这是我最终得到的最终结果。

Please enter a training file name: train.csv
Total Lines Processed: 303
Total Healthy Count: 164
Total Ill Count: 139
Averages of Healthy Patients:
[52.59, 0.56, 2.79, 129.25, 242.64, 0.14, 0.84, 158.38, 0.14, 0.59, 1.41, 0.27, 3.77, 0.00]
Averages of Ill Patients:
[56.63, 0.82, 3.59, 134.57, 251.47, 0.16, 1.17, 139.26, 0.55, 1.57, 1.83, 1.13, 5.80, 2.04]
Seperation Values are:
[54.61, 0.69, 3.19, 131.91, 247.06, 0.15, 1.00, 148.82, 0.34, 1.08, 1.62, 0.70, 4.79, 1.02]

CSV的样本将类似于13列(A-N)303行以上的值/平均值 他们中的一些人没有信息,所以被替换为?&#39; s。

2 个答案:

答案 0 :(得分:0)

您应该更新您要显示的代码。根据您最近的评论,您当前的代码是:

HPavg = sum(H_list)/(H_list)

会引发TypeError,因为您除以H_list,而不是len(H_list)。可以通过将其恢复为

来轻松修复
HPavg = sum(H_list)/len(H_list)

此外,您使用h_list中的小写h_list.append(int(row[13])),需要将其更改为H_list

答案 1 :(得分:0)

好的,我重新分析了我在做什么,并意识到我哪里出错了。当我摆脱不需要的代码的另一部分时,有一段代码我没有摆脱。感谢大家的帮助,代码现在看起来像这样。

import csv
#turn csv files into a list of lists
with open('train.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=',')
     csv_data = list(reader)

i_list = []
for row in csv_data:
    if (row and int(row[13]) > 0):
        i_list.append(int(row[13]))
H_list = []
for row in csv_data:
    if (row and int(row[13]) <= 0):
        H_list.append(int(row[13]))

Icount = len(i_list)
IPavg = sum(i_list)/len(i_list)
Hcount = len(H_list)
HPavg = sum(H_list)/len(H_list)
file = open("train.csv")
numline = len(file.readlines())

print(numline)
print("Total amount of healthy patients " + str(Icount))
print("Total amount of ill patients " + str(Hcount))
print("Averages of healthy patients " + str(HPavg))
print("Averages of ill patients " + str(IPavg))

再次感谢大家,对此感到抱歉,我非常感谢你的帮助,感谢你。