calculate a row-by-line list media in python

Asked

Viewed 1,959 times

4

question: Using the text file notes_students.dat write a program that averages each student’s grades and prints each student’s name and average. filing cabinet:

jose 10 15 20 30 40
pedro 23 16 19 22
suzana 8 22 17 14 32 17 24 21 2 9 11 17
gisela 12 28 21 45 26 10
joao 14 32 25 16 89

I used the following code:

arq=open('notas_estudantes.dat','r')
conteudo=arq.readlines()
arq.close()
soma=0
for item in conteudo:
    nom=item.split()
    for x in nom[1:300]:
        soma+=int(x)
    print(nom[0],':',soma/(len(nom)-1))

the problem he sums up the notes of the first line and divides right but he sums up the second and so on, I’m not sure how to make him add up line by line and divide correctly. being like this:

jose : 23
pedro : 48.75
suzana : 32.416666666666664
gisela : 88.5
joao : 141.4

1 answer

6


Simple: move the line of code soma=0 for after your tie for. Thus:

arq=open('notas_estudantes.dat','r')
conteudo=arq.readlines()
arq.close()
for item in conteudo:
    soma=0
    nom=item.split()
    for x in nom[1:300]:
        soma+=int(x)
    print(nom[0],':',soma/(len(nom)-1))

Thus, it will only accumulate the value for each "item" (i.e., for each student), restarting at 0 in the next item.

  • 1

    our easy... xD Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.