calculate media from a list line by line in python

3

question: Using the text file notas_estudantes.dat write a program that calculates the average of the notes of each student and prints the name and average of each student. file:

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 is that it adds the first line and divides it right but it adds more to the second and so on, I'm not sure how to add it to the line and divide it correctly. thus:

jose : 23
pedro : 48.75
suzana : 32.416666666666664
gisela : 88.5
joao : 141.4
    
asked by anonymous 07.10.2018 / 02:28

1 answer

5

Simple: Move the line of code soma=0 to after your for loop. So:

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

So, it will only accumulate the value for each "item" (ie for each student), restarting at 0 on the next item.

    
07.10.2018 / 02:35