在Python字符串数据转换为整数

问题描述 投票:1回答:2

我有以下的程序,它从一个CSV文件中读取一些数据,但它似乎是抵制一切试图无论是读了“标记”的数据为整数或将其转换成一个以后。我基于另一个我有这个程序,它是全功能与唯一的区别是,整场是我运作程序的浮动。

我试着输入下面一行到findHighest功能只是“计数器...”行之后。

**Students[0].marks = int(Students[0].marks)**

该代码运行,但没有找到数据的次数最多(它回来与96时,最高的数字是100,第二高的是96)。我也试着改变下面的行...

Students[counter].marks = row[3]

并把它改成...

**Students[counter].marks = int(row[3])**

这给了我下面的错误:

ValueError异常:无效字面对于int()与基体10: ''

我缺少的是在这里吗? : - /

导入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文件:

CSV

python python-3.x
2个回答
1
投票

我猜你有多个问题

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


0
投票

看来这是与CSV文件,而不是代码中的问题。我创建了一个从无到有的新文件,并将其学生[计数器] .marks = INT(行[3])线路工作正常。

© www.soinside.com 2019 - 2024. All rights reserved.