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

时间:2019-01-17 04:41:02

标签: python file average

我想找到inFile中列表的平均值,然后将其移至类分数。

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

4 个答案:

答案 0 :(得分:1)

您将需要:
-用空格将每一行分开,并切除除第一行外的所有项目
-将数组中的每个字符串值转换为整数
-将数组中所有这些整数值相加
-将此行的总和添加到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

答案 1 :(得分:0)

您不需要多次打开文件,而应在程序结束时关闭文件。以下是我尝试过的方法,希望对您有用:

float

答案 2 :(得分:0)

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

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

in_file = open('classgrades.txt', 'r')  # python naming style is under_score
out_file = open('classcores.txt', 'w')
all_grades = []  # if you want a class-wide average as well as individual averages

for line in in_file:
    # make a list of the things between spaces, like ["studentname", "90", "100"]
    student = line.split(' ')[0]

    # this next line includes "list comprehension" and "list slicing"
    # it gets every item in the list aside from the 0th index (student name),
    # and "casts" them to integers so we can do math on them.
    grades = [int(g) for g in line.split(' ')[1:]]

    # hanging on to every grade for later
    all_grades += grades  # lists can be +='d like numbers can

    average = int(sum(grades) / len(grades))

    # str.format() here is one way to do "string interpolation"
    out_file.write('{} {}\n'.format(student, average))

total_avg = sum(all_grades) / len(all_grades)
print('Class average: {}'.format(total_avg))
in_file.close()
out_file.close()

正如其他人指出的那样,养成关闭文件的习惯是一件好事。 此处的其他响应使用with open()(作为“上下文管理器”),这是最佳实践,因为它会自动为您关闭文件。 要处理两个文件而又没有中间的数据容器(例如Amit的d1字典),您可以执行以下操作:

with open('in.txt') as in_file:
    with open('out.txt', 'w') as out_file:
        ... do things ...

答案 3 :(得分:0)

此脚本应完成您想做的事情:

# 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