首页 > 解决方案 > 在 Python 中将字符串数据转换为整数

问题描述

我有以下程序从 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: 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

标签: pythonpython-3.x

解决方案


我猜你有多个问题

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


推荐阅读