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

时间:2019-02-04 09:12:06

标签: python python-3.x

我有一个以下程序,该程序从csv文件中读取一些数据,但它似乎拒绝所有尝试将“标记”数据读取为整数或以后再将其转换为整数的尝试。我将这个程序基于另一个我具有的功能,它具有完整的功能,唯一的真正区别是整数字段是我正在运行的程序中的浮点数。

我尝试在“ for counter ...”行之后将以下行输入到findHighest函数中。

**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文件:

CSV

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

似乎这是CSV文件而不是代码的问题。我从头开始创建了一个新文件,它的Student [counter] .marks = int(row [3])行工作正常。