从文件中提取分数?

2024-06-26 14:53:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近接到一个用python写的家庭作业,我必须制作一个假学生证的字典,并把他们在各种家庭作业中的相应分数放在一个嵌套字典中。这本有他们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

然后是他们的身份证和成绩:

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

所以我需要取最后的两位数字,把它和相应的学生放在一起。有些是重复的。到目前为止,这是我的代码,但我现在被卡住了。你知道吗

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(' ')

Tags: inidsforread字典open分数家庭作业
1条回答
网友
1楼 · 发布于 2024-06-26 14:53:53

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

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)

相关问题 更多 >