我有以下程序,它从 csv 文件中读取一些数据,但它似乎抵制所有将“标记”数据读取为整数或稍后将其转换为整数的尝试。我将此程序基于我拥有的另一个程序,该程序功能齐全,唯一真正的区别是整数字段在我的功能程序中是 float 。
我尝试在 findHighest 函数中的“for counter...”行之后输入以下行。
**Students[0].marks = int(Students[0].marks)**
代码运行,但没有找到数据中的最大数字(当最大数字为 100 时,返回 96,第二高数字为 96)。我也尝试过更改以下行...
Students[counter].marks = row[3]
并将其更改为...
**Students[counter].marks = int(row[3])**
这给了我以下错误:
ValueError:基数为 10 的 int() 的文字无效:''
我在这里缺少什么? :-/
导入csv
class Student:
def __init__(self,forename,surname,form,marks):
self.forename = ""
self.surname = ""
self.form = ""
self.marks = 0
def readFile():
Students = []
filename = "pupils.csv"
csv_file = open(filename, "r")
reader = csv.reader(csv_file)
counter = 0
for row in reader:
Students.append(Student("", "", "", 0))
Students[counter].forename = row[0]
Students[counter].surname = row[1]
Students[counter].form = row[2]
Students[counter].marks = row[3]
counter = counter + 1
return Students
def findHighest(Students):
position=0
highest = Students[0].marks
for counter in range(len(Students)):
Students[counter].marks = int(Students[counter].marks)
if Students[counter].marks > highest:
highest = Students[counter].marks
position = counter
return highest
def displayHighest(highest):
print("the highest pupil score was:", highest)
Students = readFile()
highest = findHighest(Students)
displayHighest(highest)
CSV 文件:
最佳答案
我猜你有很多问题
def findHighest(Students):
position=0
#highest is set to a string. You should set highest to 0
highest = Students[0].marks
for counter in range(len(Students)):
#why do you always set Students[0] and not Students[counter]. You always convert Students[0] to int.
Students[0].marks = int(Students[0].marks)
#As a result you always tests string again strings:
if Students[counter].marks > highest:
highest = Students[counter].marks
position = counter
return highest
这个尝试
Students[counter].marks = int(row[3])
应该是正确的,但 ValueError 可能暗示您的 CSV 内容根本不是正确的整数值。请检查您的 CSV 或按如下方式处理异常: Converting String to Int using try/except in Python
关于python - 在Python中将字符串数据转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54512975/