【问题标题】:get average from a file list从文件列表中获取平均值
【发布时间】:2014-11-13 13:14:23
【问题描述】:

所以之前我创建了一个代码,提示用户输入 5 个不同的测试分数,然后将该列表保存到 test.txt。代码效果很好! 这是我的代码:

scorefile=open('test.txt','w')

for count in range(5):

    print('Please enter test scores')

    score=input('Test score:')

    scorefile.write(str(score)+'%' + '\n')

scorefile.close()

但是现在,我遇到了一个问题。我有读取文件的代码。效果很好!但是当我尝试从列表中获取平均值时,我得到的只是 0.0。我一直在阅读我关于 python 的书来弄清楚如何使这项工作,但我现在严重卡住了。帮助? 这是我的代码:

scorefile=open('test.txt', 'r')

for line in scorefile:

    print(line, end='')

    score=scorefile

average = sum(score) / 5

print('The test average is', average)

scorefile.close()

【问题讨论】:

  • 请将您的示例代码放入代码块中。为此,请选择您的代码并按工具栏中的{} 按钮。

标签: python file store average


【解决方案1】:

这一行,score=scorefile 并没有按照您的想法执行。事实上,它根本没有做任何有用的事情。

也许你想要:

with open('test.txt') as scorefile:
    scores = [int(line.replace('%','')) for line in scorefile]
    average = sum(scores) / len(scores)

【讨论】:

    【解决方案2】:

    score=scorefile 只是将文件描述符分配给score。它实际上并没有像您预期的那样读取内容并将它们分配给score 变量。

    您需要读取文件中的行,去掉“%”字符,将每一行转换为浮点数(因为我假设它们是百分比),将它们相加并取平均值。

    像这样:

    with open('input') as in_file:
        data = in_file.readlines()
    average = sum([float(a.strip('%')) for a in data]) / len(data)
    print(average)
    

    [float(a.strip('%')) for a in data] 是一种简写符号(也称为列表推导):

    a_list = []
    for a in data:
        a_list.append(float(a.strip('%')))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 2020-11-06
      相关资源
      最近更新 更多