【问题标题】:Python: how do i sort the list inside the dictionaryPython:我如何对字典中的列表进行排序
【发布时间】:2016-04-21 18:02:59
【问题描述】:

我想按class1 中的值对score_list 进行排序。

我可以通过简单地对键进行排序来按字母顺序对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

【问题讨论】:

    标签: python list sorting dictionary average


    【解决方案1】:

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

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

    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
    

    【讨论】:

    • 我不知道您是否要尝试为每个学生存储多个考试成绩,但如果您希望这可以为解决问题提供良好的基础。
    • 我需要所有学生的姓名和他们的最后 3 个分数,而不仅仅是所有学生中最高的 3 个分数
    • 那我建议你去破解。这里有足够多的 cmets 可以帮助您入门。
    【解决方案2】:

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

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

    【讨论】:

    • 这似乎不起作用:这是我的任务 • 根据用户的表现为用户创建日志。 • 系统应存储每个学生的最后三个分数。 • 输出特定班级的测验结果,排序为: • 按字母顺序排列,每个学生的考试成绩最高 • 按最高分,从高到低 • 按平均分,从高到低 • 允许教师选择对输出数据进行排序时要查看哪个类组以及使用哪个字段。
    • 据我所知,他没有为每个学生存储多个考试成绩。编辑:好的,所以我猜他是从他的 cmets 来判断的,对不起!
    • 天哪,你太懒了,python表达想法很方便
    • 如果你在 36 小时内仍然没有自己解决这个问题,我可能会为你做功课,:),手机打字很困难
    • 杰克我已经尝试了 2 个月了现在有一段时间了,但我似乎无法弄清楚这很难我对编码很陌生,抱歉看起来像个贵族哈哈,谢谢到目前为止为您提供帮助
    猜你喜欢
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 2016-06-11
    • 2018-05-08
    • 2018-10-19
    相关资源
    最近更新 更多