第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用class-python保存在文件中

使用class-python保存在文件中

慕的地6264312 2021-05-31 06:58:21
我是python語言的新手。我想將一行保存到文件并加載文件的特定行。問題是我應(yīng)該讀?。虞d)該文件的一行作為另一個(等級)類的對象,或者將一行作為另一個類(等級)的對象保存到文件中我做到了,我想看看我做對了嗎!class Grade():    def __init__(self,student_id=0,course_id=0,score=0):        self._student_id = student_id        self._course_id = course_id        self._score = score    @property    def get(self):        return str(self._student_id)+" "+str(self._course_id)+" "+str(float(self._score))    @property    def student_id(self):        return str(self._student_id)    @property    def course_id(self):        return str(self._course_id)    @property    def score(self):        return str(self._score)    @student_id.setter    def student_id(self,student_id: int):        self._sutdent_id = student_id    @course_id.setter    def course_id(self,course_id: int):        self._course_id = course_id    @score.setter    def score(self,score: float):        self._score = scoreclass CourseUtil():    def __init__(self):        self._address = ''    def set_file(self,address):        self._address = address    def load(self,line_number):        fp = open(self._address)        for i, line in enumerate(fp):            if i+1 == line_number:                stri= line.split(" ")                stdid = int(stri[0])                corid = int(stri[1])                score = float(stri[2])                #here I want to save the #object that passed as argument to a file is it right?               grade = Grade(stdid,corid,score)                fp.close()                return(grade)        return print("None")在保存功能中,我檢查數(shù)據(jù)是否唯一,并且避免在文件末尾使用最后\ n
查看完整描述

1 回答

?
千巷貓影

TA貢獻1829條經(jīng)驗 獲得超7個贊

您使用的保存類條目行的模型效率低下。相反,您可以以更好的方式存儲數(shù)據(jù)。我假設(shè)每個學(xué)生ID是唯一且可哈希的(字符串或整數(shù))。因此,您可以簡單地擁有一本包含每個學(xué)生所有信息的字典:


student_information = {

    {student_id}: {

        course_id: {course_id},

        score: {score}

    },

    ... # more students

}

現(xiàn)在,如果您想獲取學(xué)生的信息,您可以簡單student_information[student_id]地獲取所需的數(shù)據(jù)。例如,你可以這樣做:


grade = Grade(

    student_id, 

    student_information[student_id]["course_id"], 

    student_information[student_id]["score"]

)

您可以輕松地將此字典設(shè)置為類的實例變量CourseUtil。


現(xiàn)在,@juanpa.arrivillaga 提到您應(yīng)該使用它pickle來存儲該信息(如果您想稍后返回)。使用Pickle,您可以將數(shù)據(jù)像字典一樣存儲到文件中并加載。也json可以幫助您做同樣的事情。


查看完整回答
反對 回復(fù) 2021-06-01
  • 1 回答
  • 0 關(guān)注
  • 314 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號