代码之家  ›  专栏  ›  技术社区  ›  Anonymous

如何对变量中的整数排序?

  •  -1
  • Anonymous  · 技术社区  · 10 年前

    请注意,这是在Python 3.3上

    代码如下:

    students=int(input("How many student's score do you want to sort? "))
    options=input("What do you want to sort: [Names with scores] , [Scores high to low] , [Scores averages] ? ")
    options=options.upper()
    
    if options == ("NAMES WITH SCORES") or  options == ("NAME WITH SCORE") or  options == ("NAME WITH SCORES") or options == ("NAMES WITH SCORE"):
        a=[]
        for i in range(0,students):
            name=input("Enter your scores and name: ")
            a.append(name)
    
        a.sort()
        print("Here are the students scores listed alphabetically")
        print(a)
    
    if options == ("SCORES HIGH TO LOW") or  options == ("SCORE HIGH TO LOW"):
        b=[]
        number=0
        for i in range(0,students):
            number = number+1
            print("Student "+str(number))
            name2=int(input("Enter your first score: "))
            name3=int(input("Enter your second score: "))
            name4=int(input("Enter your third score: "))
    
            b.append(name2)
            b.append(name3)
            b.append(name4)
    
        final_score = name2 + name3 + name4
        print (final_score)
        b.sort(final_score)
        print("Student "+str(number) )
        print(b)
    

    以下是代码的结果:

    >>> 
    How many student's score do you want to sort? 2
    What do you want to sort: [Names with scores] , [Scores high to low] , [Scores averages] ? scores high to low
    Student 1
    Enter your first score: 1
    Enter your second score: 2
    Enter your third score: 3
    Student 2
    Enter your first score: 3
    Enter your second score: 5
    Enter your third score: 6
    14
    Traceback (most recent call last):
      File "H:\GCSE Computing\Task 3\Task 3.py", line 31, in <module>
        b.sort(final_score)
    TypeError: must use keyword argument for key function
    >>> 
    

    我希望代码将学生的三个分数相加,并根据相应的名称对学生的总分进行排序。

    例如: (2名学生)

    学生1

    • 得分1-2
    • 得分2-4
    • 得分3-7

    (因此总数为13)

    学生2

    • 得分1-5
    • 得分2-1
    • 得分3-4

    (因此总数为10)

    (程序按从最高到最低的顺序打印)

    “学生1-15,学生2-10”

    1 回复  |  直到 10 年前
        1
  •  0
  •   Padraic Cunningham    10 年前

    你需要使用语法 key=final_score 传递排序依据的函数时:

    b.sort(key=final_score)

    但sort方法需要 function 要传递的 通过 int 添加的值 name2 + name3 + name4 不起作用。

    如果您只想对分数列表进行排序,只需调用 b.sort()

    你应该做的是使用默认字典,并使用每个名称作为关键字,并将所有分数存储在列表中:

    from collections import defaultdict
    
    
    d = defaultdict(list)
    
    for _ in range(students):
        name = input("Enter your name: ")
        scores = input("Enter your scores separated by a space: "
        # add all scores for the user to the list
        d[name].extend(map(int,scores.split()))
    

    要显示平均值、总值和最大值,这是微不足道的:

    # from statistics import mean will work for python 3.4
    
    for k,v in d.items():
           print("Scores total for {} is {}".format(k,sum(v)))
           print("Scores average for {} is {}".format(k,sum(v)/len(v))) # mean(v) for python 3,4
           print("Highest score  for {} is {}".format(k, max(v)))
    

    按最高用户总分排序的打印:

    print("The top scoring students from highest to lowest are:")
    for k,v in sorted(d.items(),key=lambda x:sum(x[1]),reverse=True):
        print("{} : {}".format(k,sum(v)))
    

    现在你有一个字典,其中学生的名字是关键,每个学生的分数都存储在一个列表中。

    实际上,您应该添加一个try/except,接受用户输入并验证其格式是否正确。