簡體   English   中英

在 Python 中將字符串數據轉換為整數

[英]Converting string data to integer in 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

我猜你有很多問題

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

這似乎是 CSV 文件的問題,而不是代碼的問題。 我從頭開始創建了一個新文件,它的 Students[counter].marks = int(row[3]) 行工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM