# Developers Planet

Lenard February 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_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):
``````

Mike Müller February 2016

I would recommend doing something like this:

``````data = {}
with open('scores.txt') as fobj:
for line in fobj:
name, score = line.split()
data.setdefault(name, []).append(int(score))

for name, scores in data.items():
avg = sum(scores[-3:]) / min(3, len(scores))
print('{} your average was {}'.format(name, avg))
``````

Output:

``````james your average was 10.0
``````

Sorted by average; highest first:

``````from operator import  itemgetter

for name, scores in sorted(data.items(), key=itemgetter(1), reverse=True):
avg = sum(scores[-3:]) / min(3, len(scores))
print('{} your average was {}'.format(name, avg))
``````

Output:

``````james your average was 10.0
``````

user3100115 February 2016

You can also use the `defaultdict` class from the `collections` module and the `mean` function from the `statistics` module.

Demo:

``````>>> from collections import defaultdict
>>> from statistics import mean
>>> data = defaultdict(list)
>>> with open('score.txt') as f:
...     for line in f:
...         name, score = line.split()
...         data[name].append(float(score))
...
...
>>> data
defaultdict(<class 'list'>, {'zack': [5.0, 5.0, 5.0], 'james': [10.0, 10.0, 10.0], 'max': [3.0, 3.0, 3.0], 'lenard': [1.0, 1.0, 10.0]}
>>> for name, score in data.items():
...     print('{} your average was {}'.format(name, mean(score)))
...
``````