Skip to main content
 首页 » 编程设计

python之从文件中提取成绩

2025年05月04日9lhb25

我最近在 python 中得到了一项家庭作业,我必须制作一个假学生 ID 的字典,并将各种家庭作业的相应成绩放入一个嵌套字典中。我可以毫无问题地制作带有他们 ID 的字典,但我似乎无法将他们相应的成绩放入其中。 文件内容的一个例子是:

807-49-0073 
658-30-1272 
544-78-7923 
709-40-8165 
492-42-7987 
503-27-1729 
840-12-4303 
169-09-7157 
560-33-3099 
278-16-5335 
097-26-3512 
267-10-7633 
979-49-6579 
821-67-0672 
393-36-5485 

然后是他们的 ID 和成绩:

267-10-7633 66 
709-40-8165 71 
097-26-3512 78 
807-49-0073 83 
169-09-7157 73 
278-16-5335 79 
979-49-6579 79 
544-78-7923 85 
560-33-3099 73 
840-12-4303 62 
821-67-0672 87 
503-27-1729 8 
267-10-7633 85 
979-49-6579 60 
503-27-1729 62 
821-67-0672 62 
393-36-5485 15 
560-33-3099 38 
097-26-3512 80 
658-30-1272 85 
278-16-5335 84 
169-09-7157 70 
840-12-4303 73 
544-78-7923 60 
560-33-3099 87 
840-12-4303 75 
979-49-6579 96 
492-42-7987 85 
544-78-7923 72 
169-09-7157 82 
278-16-5335 67 
709-40-8165 96 
393-36-5485 87 
097-26-3512 85 
821-67-0672 86 
278-16-5335 97 
393-36-5485 73 
503-27-1729 78 
979-49-6579 24 
821-67-0672 87 
544-78-7923 73 
709-40-8165 34 
097-26-3512 73 
840-12-4303 100 
807-49-0073 75 
267-10-7633 74 
658-30-1272 94 
492-42-7987 87 

所以我需要取最后一位2位数字和对应的学生放在一起。有些是重复的。到目前为止,这是我的代码,但我目前卡住了。

def create_dictionary(idfilename, hwfilename): 
    hwL = [] 
    dict1 = {} 
    dict2 = {'hw': hwL} 
 
    ids = open(idfilename, 'r').read().splitlines() 
    hws = open(hwfilename, 'r').read().splitlines() 
 
    for i in ids: 
        dict1[i] = dict1.get(i, dict2) 
 
    for k in hws: 
        hwL = k.split(' ') 

请您参考如下方法:

我现在无法调试,但这应该很接近:

import csv 
#assuming the files are .csvs 
def create_dictionary(idfilename, hwfilename): 
    #declare the field names of the dictionaries so we can refer to them later 
    field_names1 = ['id'] 
    field_names2 = ['id','grade'] 
    dictOf_Ids = csv.DictReader(open(idfilename,fieldnames=field_names1)) 
    dictOf_hw = csv.DictReader(open(hwfilename,fieldnames=field_names2)) 
    #will look something like this: [{'id':'560-33-3099','grades':[76,56,42]}] 
    listOf_dictionaries =[{}]    
 
    #read through the records in the id dictionary line by line 
    for id in dictOf_Ids: 
        #each id will have its own list of grades 
        grades = [] 
        #read through the records in the hw dictionary line by line 
        for hw in dictOf_hw: 
            #if the ids match, get the grade from the hw dict and add it to our list of grades for that id 
            if id.get('id') == hw.get('id'): 
                grade = hw.get('grade') 
                grades.append(grade) 
            else: 
                #do nothing because the id's don't match 
                pass 
        #add the dictionary to the list 
        dict = {'id':id,'grades':grades} 
        listOf_dictionaries.append(dict)