【问题标题】:File IO - Calculate Grades文件 IO - 计算成绩
【发布时间】:2014-11-04 21:12:52
【问题描述】:

我刚开始学习如何在 python 中读取和写入文件,我们被要求从名为“score.txt”的文件中读取。 'score.txt' 看起来像这样

比利 0.03 74 0.03 79 0.03 72 0.03 69 0.03 81 0.03 75 0.03 73 0.03 70 0.08 75 0.08 73 0.25 82 0.25 71 0.10 28

鲍勃 0.03 84 0.03 79 0.03 87 0.03 90 0.03 85 0.03 82 0.03 86 0.03 83 0.08 87 0.08 89 0.25 82 0.25 84 0.10 80

乔 0.03 66 0.03 63 0.03 89 0.03 65 0.03 57 0.03 70 0.03 64 0.03 67 0.08 65 0.08 62 0.25 70 0.25 61 0.10 27

每一行以一个名字开头,后面的第一个值是分数的权重,后面是分数本身。这会根据需要重复多次,但格式总是正确的。

我的最终输出需要类似于以下内容:

比利:70.68 - C

鲍勃:83.86 - B

乔:61.84 - D

班级平均分:72.12

我真的不确定我什至想如何开始解决这个问题。到目前为止,这是我拥有的代码,所有这些都是创建一个包含所有信息的列表。

我知道我需要能够删除我可以使用 myList.pop(0) 的第一个索引,这将删除名称,但我不确定如何将第一个索引和第二个索引相乘互相索引,然后继续前进。

def main():

    grade()

def grade():

    inFile = open("score.txt", "r")
    outFile = open("score_report.txt", "w")
    myList = []
    flag = True

    while flag:
        theLine = inFile.readline()
        if len(theLine) == 0:
            flag = False
        #outFile.write(theLine)                                                                                                                                                                                                                                               
        myList.append(theLine)
    print(myList)

    inFile.close()
    outFile.close()

main()

【问题讨论】:

    标签: file python-3.x file-io


    【解决方案1】:

    这是一个开始(未经测试),还有几件留给你。

    with open("score.txt", "r") as imp, open("score_report.txt", "w") as out:
        n, class_sum = 0, 0
        for lime in imp:
            items = line.split()
            if not len(items) % 2:
                raise ValueError('line has even number of items')
            it = iter(items)
            name = next(it)  # cannot fail because odd number of items
            wt_score = 0
            for wt in it:
                wt_score += wt * next(it)  # ditto
            out.write(name, wt_score)  # plus grade
            n += 1
            class_sum += score
        # out.write( <class summary>)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 2019-08-25
      • 2017-03-01
      • 1970-01-01
      • 2015-05-31
      相关资源
      最近更新 更多