samedi 6 février 2016

Finding the average of a list

So, guys I've got some code that reads a file:

lenard  1
lenard  1
lenard  10
max 3
max 3
max 3
zack    5
zack    5
zack    5
james   10
james   10
james   10

From the file a list is created in the form [10,10,10]. After this is done I calculate the average of the list and outputs it on the screen.

My code only partially works and does this instead:

10
18
28

and the average that it finds not the one for the list last_3_scores.

My question is why does the first number in the list keep on getting added together and the average of that is calculated instead of the average of last_3_scores.

Heres my code:

with open('StudentsScoreA.txt', "r+") as file:
    file.seek(0)
    scores = file.readlines()

scores_pairs = [score.strip().split('\t') for score in scores]
avg_with_name=[]
avg=[]
name_list=[]
last_3_scores=[]



for score in reversed(scores_pairs):
    name=score[0]
    name_list.append(name)

    for item in name_list:
        if name_list.count(name) > 1:
            name_list.remove(name)
            print(name_list)

for item in name_list:
    for score in reversed(scores_pairs):
        name=score[0]

        if name == item and len(last_3_scores) <= 3:
            last_3_scores.append(score[1])

        elif len(last_3_scores) == 3:
            print(last_3_scores)

    for items in last_3_scores:
        item=int(items)
        avg.append(item)
        print(sum(avg))
        mean=sum(avg)/len(last_3_scores)
        avg_with_name.append([name,mean])
        del last_3_scores[:]


for name, average in reversed(avg_with_name):
    print('{} your average was {}'.format(name,average))

Aucun commentaire:

Enregistrer un commentaire