函数按字母顺序生成输出,而不是按平均分数排序

时间:2015-10-15 16:30:53

标签: python mysql sqlite

此功能显示3个最新结果中数据库中每个人的平均得分。输出按名称排序,如何按平均顺序排列,从最高到最低。

def averagescore():
    allnames = []
    itr = cursor.execute("SELECT name FROM "+group+" GROUP BY name;").fetchall()#lists names in database
    for x in itr:
        if x not in allnames:
            allnames.append(x[0])
        else:
            False
    allnames.sort()
    avg = 0
    number = 0

    for name in allnames:
        cursor.execute("SELECT total FROM "+group+" WHERE (\""+name+"\") = NAME ORDER BY DATE DESC LIMIT 3;")#3 most recent scores
        scores =(cursor.fetchall())     

        scores = [i[0] for i in scores]        
        avg = sum(scores)/len(scores)
        print(name,"'s average is: ",avg,". From (up to) 3 most recent scores which were: ",scores,)
        avg = 0

输出结果为:

AZ 's average is:  0.0 . From (up to) 3 most recent scores which were:  [0]
ED 's average is:  0.6666666666666666 . From (up to) 3 most recent scores which were:  [0, 1, 1]
JAKE 's average is:  2.0 . From (up to) 3 most recent scores which were:  [0, 4]
SAM 's average is:  0.0 . From (up to) 3 most recent scores which were:  [0]
ZAC 's average is:  0.0 . From (up to) 3 most recent scores which were:  [0]

我希望它是:

JAKE 's average is:  2.0 . From (up to) 3 most recent scores which were:  [0, 4]
ED 's average is:  0.6666666666666666 . From (up to) 3 most recent scores which were:  [0, 1, 1]

ETC

2 个答案:

答案 0 :(得分:1)

你的意思是这样的吗?

(请参见此处:https://wiki.python.org/moin/HowTo/Sorting

#!/usr/bin/python

# datastruct
# name, avg, [scores]

datastruct = [
    ['AZ', 0.0, [0]],
    ['ED', 0.6666666666666666, [0, 1, 1]],
    ['JAKE', 2.0, [0, 4]],
    ['SAM', 0.0, [0]],
    ['ZAC', 0.0, [0]]
]

print('before')
for item in datastruct:
    print(item)

print('after')
for item in sorted(datastruct, key=lambda k: k[1], reverse=True):
    print("{}'s avg is: {}. From (up to 3) most recent scores which were: {}".format(item[0], item[1], item[2]))

答案 1 :(得分:1)

您可以从两个sql查询构建一个组合记录列表,然后按@davejagoda的答案平均排序。

关于你的需求,第一个for循环,我会使用allnames的集合,然后将其转换为排序列表。之后,我将构建一个仅records的{​​{1}}列表。然后,我会像您一样使用这些名称执行第二次数据库查询,并使用[{'name': 'foo'}, {'name': 'bar'}, ...]avg就地更新该记录。

在此之后,我将按scores按降序排列记录records并打印出结果。

为此,您的代码将如下所示:

avg