Как найти среднее значение для файла, а затем поместить его в другой файл - PullRequest
0 голосов
/ 17 января 2019

Я хочу найти среднее значение списка в файле, а затем переместить его в класс оценок.

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 голосов
/ 17 января 2019

Этот скрипт должен выполнить то, что вы пытаетесь сделать, я думаю:

# 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
0 голосов
/ 17 января 2019

Вам понадобится:
- разбить каждую строку на пробелы и вырезать все элементы, кроме первого
- преобразовать каждое строковое значение в массиве в целое число
- суммировать все эти целочисленные значения в массиве
- добавить сумму для этой строки к 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
0 голосов
/ 17 января 2019

Извиняюсь, если это что-то сложное, я стараюсь предоставить ключевые слова / фразы для вас, чтобы найти, чтобы узнать больше.

Предполагается, что вы ищете отдельное среднее значение для каждого студента:

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 ...
0 голосов
/ 17 января 2019

вам не нужно открывать файл много раз, и вы должны закрыть файлы в конце вашей программы. Вот то, что я пытался, надеюсь, это работает для вас:

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