查找列表的平均值

时间:2016-02-06 20:27:27

标签: list python-3.x if-statement for-loop average

所以,我们有一些代码可以读取文件:

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

从文件中以[10,10,10]的形式创建列表。完成此操作后,我计算列表的平均值并将其输出到屏幕上。

我的代码只是部分有效,而是这样做:

10
18
28

和它找到的平均值不是列表last_3_scores。

我的问题是为什么列表中的第一个数字会一直加在一起,而是计算平均数而不是last_3_scores的平均值。

继承我的代码:

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

2 个答案:

答案 0 :(得分:1)

我建议做这样的事情:

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

输出:

james your average was 10.0
zack your average was 5.0
max your average was 3.0
lenard your average was 4.0

按平均排序;最高的第一名:

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

输出:

james your average was 10.0
zack your average was 5.0
max your average was 3.0
lenard your average was 4.0

答案 1 :(得分:0)

您还可以使用collections模块中的defaultdict类和statistics模块中的mean函数。

演示:

>>> 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)))
... 
zack your average was 5.0
james your average was 10.0
max your average was 3.0
lenard your average was 4.0