Python:我如何对字典中的列表进行排序

时间:2016-04-21 18:03:00

标签: python list sorting dictionary average

我想按score_list的值class1排序{。}}。

我可以通过简单地对键进行排序来按字母顺序对score_list进行排序,但我无法弄清楚如何从数字到数字从最大到最小排序。

此外,我希望score_list仅存储最后3个输入,如果可能,我希望找到每个学生最后3个分数的平均值。

enter code here:




score_list = []
class1 = {}
what_class = input ("what class would you like?")
if what_class == ("1") :
    print("class1 results")
    student_name =input("name?")
    score = input("score?")
    choose = input("do you want to entre another student? y,n")
    while choose == "y":
        student_name =input("name?")
        score = input("score?")
        score_list.append(score)
        choose = input("do you want to entre another score? y,n")
        class1.setdefault(student_name,score_list)
        if choose == "n":
            sorted_names = sorted(class1.keys())
            print(class1)

class1_items = class1.items()
print (type(class1_items))

for i in class1_items:
    print (i)

如果有人可以帮助我,我会非常感谢它 谢谢你的帮助

[]更好地了解目标:1

enter code here
import heapq
from collections import deque
print("alphabetical(type:A),highest to lowest(type:B),Average(type:C)")
student_name = input("ENTER NAME")
result_type = input ("WHICH TYPE OF RESULTS WOULD YOU LIKE?")
which_class = input ("which class?")

if result_type == ("A") or result_type == ("a"):
    print("alphabetical order(type:A)")


if result_type == ("B") or result_type == ("b"):
    print("results in highest to lowest.")
    score_list = deque(maxlen=3)
    scores = input("Please enter your score.")
    choose = input("do you want to entre another score? y,n")
    while choose != "n":
        scores = input("Please enter your score.")
        choose = input("do you want to entre another score? y,n")
        score_list.append(scores)
        if choose != "y" :
            print(score_list)
            print((student_name)+"'s:"+"lowest to largest"+str(heapq.nsmallest(3, score_list)))
            print((student_name)+"'s:"+"largest to lowest"+str(heapq.nlargest(3, score_list)))

if result_type == ("C") or result_type == ("c"):
    print("results in average order.")
    score_list = deque(maxlen=3)
    scores = input("Please enter your score.")
    choose = input("do you want to entre another score? y,n")
    while choose != "n":
        scores = input("Please enter the  scores.")
        choose = input("do you want to entre another score? y,n")
        score_list.append(int(scores))
        #print(len(score_list))
        #print(sum(score_list))
        total = (int(sum(score_list)))
        length = (int(len(score_list)))
        average= (total)/(length)
        if choose != "y" :
            print(student_name+"'s "+"average score:"+str(average))
           #print("average: " +str(average))

这是我如何改进它,我仍然无法弄清楚按字母顺序排序的部分。

the objectives to help you know what i am trying to do

2 个答案:

答案 0 :(得分:0)

更新,您应该能够粘贴并运行以下代码 但是,你需要自己包装输入循环,这意味着,连接接口/函数调用

import json
class Quize():
    def __init__(self):
        self.db = {}

    def createClass(self, class_name):
        self.db[class_name] = {}

    def createUser(self, class_name, user_name):
        self.db[class_name][user_name] = []

    def addScore(self, class_name, user_name, score):
        self.db[class_name][user_name].append(score)
        self.db[class_name][user_name] = self.db[class_name][user_name][-3:]

    def printClass(self, class_name, order = None):
        if not order:
            print json.dumps(self.db[class_name], indent=4)
        else:
            to_sort = self.db[class_name]
            print 'order', order
            if order == 'by highest':
                print sorted([ [max(to_sort[name]), name] for name in to_sort ], cmp = lambda x, y : y[0] - x[0])
            if order == 'by lowest':
                print sorted([ [min(to_sort[name]), name] for name in to_sort ], cmp = lambda x, y : x[0] - y[0])
            if order == 'by average':
                print sorted([ [sum(to_sort[name]) / len(to_sort[name]), name] for name in to_sort ], 
                                cmp = lambda x, y : y[0] - x[0])
            if order == 'by name':
                print sorted([ [to_sort[name], name] for name in to_sort ], cmp = lambda x, y : x[1] > y[1])
    def printUser(self, class_name, user_name):
        print json.dumps(self.db[class_name][user_name], indent=4)

    def dump(self):
        print json.dumps(self.db, indent = 4)

ins = Quize()
ins.createClass('0302')
ins.createUser('0302', 'jack')
ins.createUser('0302', 'tom')

ins.addScore('0302', 'jack', 99)
ins.addScore('0302', 'jack', 92)
ins.addScore('0302', 'tom', 99)
ins.addScore('0302', 'tom', 92)
ins.addScore('0302', 'tom', 19)
ins.addScore('0302', 'tom', 29)
ins.addScore('0302', 'tom', 66)

ins.printClass('0302', 'by highest')
ins.printClass('0302', 'by lowest')
ins.printClass('0302', 'by average')
ins.printClass('0302', 'by name')

ins.printUser('0302', 'tom')
ins.printUser('0302', 'jack')
ins.printClass('0302')

ins.addScore('0302', 'jack', 11)
ins.addScore('0302', 'jack', 37)
ins.addScore('0302', 'tom', 80)
ins.addScore('0302', 'tom', 72)

ins.printClass('0302', 'by highest')
ins.printClass('0302', 'by lowest')
ins.printClass('0302', 'by average')
ins.printClass('0302', 'by name')

ins.printUser('0302', 'tom')
ins.printUser('0302', 'jack')
ins.printClass('0302')

答案 1 :(得分:0)

这里有很多问题,但我会讨论一些问题。您需要确保将输入转换为int(),否则您将对字符串进行数学运算,这会导致问题。其次,最重要的是,字典不是有序的,所以你永远不会得到相同的最后3个条目。

您可以使用列表推导来获取成绩并对其进行排序,这是其他事情之后的第一件事:因为输入顺序无关紧要。对于接下来的两个,您不能使用字典值,您必须参考您用来跟踪输入成绩的列表。

grade_list = []
class1 = {}
if input('what class would you like? ') == '1':
    while True:
            student_name = input('name? ')
            score = int(input('score? ')) # must convert input to int
            grade_list.append(score)
            class1[student_name] = score
            if input('do you want to enter another student? ') == 'y':
                pass
            else:
                # fetch grades
                grades = [v for k, v in class1.items()]
                # print highest to lowest
                print(sorted(grades, reverse=True))
                # print last 3 grades
                print(grade_list[-3:])
                # print avg of last 3 grades
                print(sum(grade_list[-3:]) / 3)
                break

输出

what class would you like? 1
name? Abby
score? 11
do you want to enter another student? y
name? Bobby
score? 22
do you want to enter another student? y
name? Charles
score? 33
do you want to enter another student? y
name? Damon
score? 44
do you want to enter another student? n
[44, 33, 22, 11]
[22, 33, 44]
33.0