Python 如何找到一个文件的平均值,然后将其放入另一个文件中

Python 如何找到一个文件的平均值,然后将其放入另一个文件中,python,file,average,Python,File,Average,我想找到列表填充的平均值,然后我想把它移到课堂分数上 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('classgra

我想找到列表填充的平均值,然后我想把它移到课堂分数上

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

您不需要多次打开文件,应该在程序结束时关闭这些文件。以下是我尝试的内容,希望这对您有用:

d1 = {}
with open(r'classgrades.txt','r') as fp:
    for line in fp:
        contents = line.strip().split(' ')
        # create mapping of student and his numbers
        d1[contents[0]] = map(int,contents[1:])

with open(r'classscores.txt','w') as fp:
    for key, item in d1.items():
        biggest = min(item)
        smallest = max(item)
        print(biggest - smallest)
        # average of all numbers
        avg = sum(item)/len(item)
        fp.write("%s %s\n"%(key,avg))
您需要:
-用空格分隔每行,并将除第一行以外的所有项目切掉
-将数组中的每个字符串值转换为整数
-对数组中的所有整数值求和
-将此行的总和添加到总计中
-将这些值的长度(数字的数量)添加到总数中

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

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

抱歉,如果这是一种高级,我会尝试提供关键字/短语供您搜索以了解更多信息

假设您正在查找每个学生的单独平均值:

in_file=open('classgrades.txt','r')35; python命名风格在_分数以下
out\u file=open('classcores.txt','w')
如果你想获得全班平均成绩和个人平均成绩,则所有大学成绩=[]
对于\u文件中的行:
#在空格之间列一个清单,比如[“studentname”,“90”,“100”]
学生=行分割(“”)[0]
#下一行包括“列表理解”和“列表切片”
#它获取列表中除第0个索引(学生姓名)之外的所有项目,
#然后将它们“强制”为整数,这样我们就可以对它们进行数学运算。
等级=[int(g)表示第行中的g。拆分(“”)[1:]
#留心每一个年级,待会儿再说
所有的分数都可以是+='d,就像数字一样
平均值=整数(总和(等级)/长度(等级))
#str.format()这里是执行“字符串插值”的一种方法
out_file.write('{}{}\n'.格式(学生,平均))
总平均值=总和(所有等级)/长度(所有等级)
打印('Class average:{}'。格式(总平均值))
in_file.close()中
out_file.close()
正如其他人指出的,养成关闭文件的习惯是很好的。 这里的其他响应使用
和open()
(作为“上下文管理器”),这是最佳做法,因为它会自动为您关闭文件。 要使用两个文件而不在两者之间使用数据容器(如Amit的
d1
字典),您可以执行以下操作:

打开('in.txt'),如在_文件中:
以open('out.txt','w')作为out\u文件:
... 做事。。。

这个脚本应该可以完成您想要做的事情,我认为:

# define a list data structure to store the classgrades
classgrades = []

with open( 'classgrades.txt', 'r' ) as infile:
  for line in infile:
    l = line.split()
    # append a dict to the classgrades list with student as the key
    # and value is list of the students scores.
    classgrades.append({'name': l[0], 'scores': l[1:]})

with open( 'classscores.txt', 'w' ) as outfile:
  for student in classgrades:

    # get the students name out of dict.
    name = student['name']

    # get the students scores. use list comprehension to convert 
    # strings to ints so that scores is a list of ints.
    scores = [int(s) for s in student['scores']]

    # calc. total 
    total = sum(scores)

    # get the number of scores.
    count = len( student['scores'] )

    # calc. average
    average = total/count
    biggest = max(scores)
    smallest = min(scores)
    diff = ( biggest - smallest )

    outfile.write( "%s %s %s\n" % ( name, diff , average ))
运行上述代码将创建一个名为classscores.txt的文件,其中包含以下内容:

Chapman 45 79.33333333333333
Cleese 10 85.75
Gilliam 7 78.66666666666667
Idle 0 91.0
Jones 100 63.57142857142857
Palin 10 85.0

首先,你不应该多次打开“classgrades.txt”。一次就够了。进入循环后,拆分当前行,将数字行字符串转换为数字,相加,除以计数,将字符串的第一个元素和平均值写入输出文件。。。入门级Python类中的典型家庭作业。