首页 > 解决方案 > 如何找到一个文件的平均值然后将其放入另一个文件

问题描述

我想找到 inFile 列表的平均值,然后我想将它移动到 classescores。

classgrades.txt是:

Chapman 90 100 85 66 80 55    
Cleese 80 90 85 88    
Gilliam 78 82 80 80 75 77    
Idle 91    
Jones 68 90 22 100 0 80 85    
Palin 80 90 80 90

classcores.txt是空的

这就是我目前所拥有的......我该怎么办?

inFile = open('classgrades.txt','r')
outFile = open('classscores.txt','w')

for line in inFile:
  with open(r'classgrades.txt') as data:
    total_stuff = #Don't know what to do past here

biggest = min(total_stuff)
smallest = max(total_stuff)
print(biggest - smallest)
print(sum(total_stuff)/len(total_stuff))

标签: pythonfileaverage

解决方案


您将需要:
- 用空格分割每一行并切掉除第一个以外的所有项目
- 将数组中的每个字符串值转换为整数
- 将数组中的所有整数值
相加 - 将此行的总和添加到 total_sum
- 添加这些值的长度(数字的数量)到 total_numbers

然而,这只是问题的一部分......我将把剩下的留给你。此代码不会写入新文件,它只会取第一个文件中所有数字的平均值。如果这不是你所要求的,那么试着玩弄这些东西,你应该能够弄清楚。

inFile = open('classgrades.txt','r')
outFile = open('classscores.txt','w')
total_sum = 0
total_values = 0
with open(r'classgrades.txt') as inFile:
  for line in  inFile:
    # split by whitespace and slice out everything after 1st item
    num_strings = line.split(' ')[1:] 

    # convert each string value to an integer
    values = [int(n) for n in num_strings]

    # sum all the values on this line
    line_sum = sum(values)

    # add the sum of numbers in this line to the total_sum
    total_sum += line_sum

    # add the length of values in this line to total_values
    total_numbers += len(values)

average = total_sum // total_numbers  # // is integer division in python3
return average

推荐阅读