简体   繁体   English

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

[英]Converting string data to integer in Python

I have the following program that reads some data from a csv file but it seems to be resisting all attempts to either read the "marks" data as an integer or convert it to one later on.我有以下程序可以从 csv 文件中读取一些数据,但它似乎拒绝了将“标记”数据作为整数读取或稍后将其转换为整数的所有尝试。 I based this program on another I have which is fully functional with the only real difference that the integer field was a float in my functioning program.我将此程序基于另一个我拥有的功能齐全的程序,唯一真正的区别是整数字段在我的功能程序中是一个浮点数。

I've tried entering the following line into the findHighest function just after the "for counter..." line.我尝试在“for counter...”行之后将以下行输入到 findHighest 函数中。

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

The code runs but doesn't find the highest number in the data (it comes back with 96 when the highest number is 100, the second highest is 96).代码运行但未找到数据中的最高数字(当最高数字为 100 时返回 96,第二大数字为 96)。 I've also tried altering the following line...我也试过改变以下行...

Students[counter].marks = row[3]

and changed it to...并将其更改为...

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

This gives me the following error:这给了我以下错误:

ValueError: invalid literal for int() with base 10: '' ValueError:int() 的无效文字以 10 为基数:''

What am I missing here?我在这里缺少什么? :-/ :-/

import csv导入 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 File: CSV 文件:

CSV

I guess you have multiple problems我猜你有很多问题

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

This try这次尝试

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

should be correct but the ValueError can be a hint that your content of your CSV is not at all lines a correct integer value.应该是正确的,但 ValueError 可能暗示您的 CSV 内容根本不是正确的整数值。 Please check your CSV or handle the exception like this: Converting String to Int using try/except in Python请检查您的 CSV 或处理这样的异常: Converting String to Int using try/except in Python

It seems this was a problem with the CSV file rather than the code.这似乎是 CSV 文件的问题,而不是代码的问题。 I created a new file from scratch and it the Students[counter].marks = int(row[3]) line works fine.我从头开始创建了一个新文件,它的 Students[counter].marks = int(row[3]) 行工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM