请问如何编写python成绩排序

该怎么在下面的代码里添加一个可以升序和降序的成绩排序功能呀

from search import search_by_id

stat_submenu = '''

    5 统计 ---|---  1 学生总分   
              |---  2 单科总成绩、平均分
              |---  3 单科最高分
              |---  4 总成绩排序
              |---  0 返回

'''

def scores_sum(db, sid):
    sum = 0
    if search_by_id(db, sid) == {}:
        print('  - %s does not exist.' % sid)
        sum = -1
    else:
        for i in db:
            if i['studentID'] == sid:
                sum = i['score_1'] + i['score_2'] + i['score_3']
    return sum

def object_sum(db, object_n):
    avg = 0
    sum = 0
    total = len(db)
    for i in db:
        sum += float(i[object_n])
    avg = sum / total
    return sum, avg

def object_max(db, object_n):
    max = 0
    for i in db:
        temp = float(i[object_n])
        if temp > max:
            max = temp
    return max

def db_stat(db):
    temp_db = db
    while True:
        print(stat_submenu)
        option = input('  > Enter your option:')
        if option == '0':
            break
        elif option == '1':
            sid = input('  >> Student ID:')
            sum = scores_sum(db, sid.strip())
            if sum != -1:
                print('  - Sum_Score of %s is %f' % (sid, sum))
            continue
        elif option == '2':
            object_name = input('  > Object name:')
            sum, avg = object_sum(db, object_name.strip())
            print('  - Sum of the object %s is %f' % (object_name, sum))
            print('  - Average of the object %s is %f' % (object_name, avg))
            continue
        elif option == '3':
            object_name = input('  > Object name:')
            max = object_max(db, object_name.strip())
            print('  - The maximum of the object %s is %f' % (object_name, max))
            continue
        elif option == '4':
            print('  - To be coded.')
            continue
        else:
            print('  - Inputting WRONG!')
            continue


if __name__ == '__main__':
    db_stat([])
    pass

from search import search_by_id
 
stat_submenu = '''
    5 统计 ---|---  1 学生总分   
              |---  2 单科总成绩、平均分
              |---  3 单科最高分
              |---  4 总成绩排序
              |---  0 返回
'''
 
def scores_sum(db, sid):
    sum = 0
    if search_by_id(db, sid) == {}:
        print('  - %s does not exist.' % sid)
        sum = -1
    else:
        for i in db:
            if i['studentID'] == sid:
                sum = i['score_1'] + i['score_2'] + i['score_3']
    return sum
 
def object_sum(db, object_n):
    avg = 0
    sum = 0
    total = len(db)
    for i in db:
        sum += float(i[object_n])
    avg = sum / total
    return sum, avg
 
def object_max(db, object_n):
    max = 0
    for i in db:
        temp = float(i[object_n])
        if temp > max:
            max = temp
    return max

def sort_sum(db):
    l = list()
    d = dict()
    for i in db:
        d[i['studentID']] = i['score_1'] + i['score_2'] + i['score_3']
    
    # 升序
    l.append(sorted(d.items(), key=lambda s:s[1]))
    # 降序
    l.append(sorted(d.items(), key=lambda s:s[1], reverse=True))
    return l

def db_stat(db):
    temp_db = db
    while True:
        print(stat_submenu)
        option = input('  > Enter your option:')
        if option == '0':
            break
        elif option == '1':
            sid = input('  >> Student ID:')
            sum = scores_sum(db, sid.strip())
            if sum != -1:
                print('  - Sum_Score of %s is %f' % (sid, sum))
            continue
        elif option == '2':
            object_name = input('  > Object name:')
            sum, avg = object_sum(db, object_name.strip())
            print('  - Sum of the object %s is %f' % (object_name, sum))
            print('  - Average of the object %s is %f' % (object_name, avg))
            continue
        elif option == '3':
            object_name = input('  > Object name:')
            max = object_max(db, object_name.strip())
            print('  - The maximum of the object %s is %f' % (object_name, max))
            continue
        elif option == '4':
            print(sort_sum(db))
            continue
        else:
            print('  - Inputting WRONG!')
            continue
 
 
if __name__ == '__main__':
    db_stat([])
    pass
 

使用sort()或sorted()。
推荐使用sorted(),因为sorted()不会改变原内容。
如果要升序,括号内加上reverse = True

分析:

方法一:先按成绩冒泡排序,再按名字冒泡排序,再按年龄冒泡排序

方法二:以成绩为排序要点,在该冒泡排序内,如果成绩相等,等判断名字,如果连名字都相等,就判断年龄,按要求调换位置

代码:


代码一:

class student(): #创建学生类

def inputInfo(self,st):

lis=list(st)

self.name=lis[0]

self.age=int(lis[1])

self.grade=int(lis[2])

def getName(self):

return self.name

def getAge(self):

return self.age

def getGrade(self):

return self.grade

n=int(input()) #输入部分

students=[]

while n:

n-=1

st=student()

st.inputInfo(input().split())

students.append(st)

for j in range(len(students)-1): #根据成绩排序,忽略成绩相等的情况

for i in range(len(students)-1-j):

if students[i].getGrade()>students[i+1].getGrade():

students[i],students[i+1]=students[i+1],students[i]

for j in range(len(students)-1): #遍历找到成绩相等的情况,按姓名排序

for i in range(len(students)-1-j):

if students[i].getGrade()==students[i+1].getGrade():

if students[i].getName()>students[i+1].getName():

students[i],students[i+1]=students[i+1],students[i]

for j in range(len(students)-1): #遍历找到成绩名字都相等的情况,按年龄排序

for i in range(len(students)-1-j):

if students[i].getGrade()==students[i+1].getGrade():

if students[i].getName()==students[i+1].getName():

if students[i].getAge()>students[i+1].getAge():

students[i],students[i+1]=students[i+1],students[i]

for i in students: #输出

print(i.getName(),i.getAge(),i.getGrade(),sep=' ')

```python

#######################################

#代码二:

#######################################

class student(): #创建学生类

def inputInfo(self,st):

lis=list(st.split())

self.name=lis[0]

self.age=int(lis[1])

self.grade=int(lis[2])

def getName(self):

return self.name

def getAge(self):

return self.age

def getGrade(self):

return self.grade

students=[] #输入部分

n=int(input())

while n:

n-=1

st=student()

st.inputInfo(input())

students.append(st)

for i in range(len(students)-1):

for j in range(len(students)-1-i): #按成绩排序

if students[j].getGrade()>students[j+1].getGrade():

students[j],students[j+1]=students[j+1],students[j]

elif students[j].getGrade()==students[j+1].getGrade():#当过程中遇到成绩相等的时候,按名字排序

if students[j].getName()>students[j+1].getName():

students[j],students[j+1]=students[j+1],students[j]

elif students[j].getName()==students[j+1].getName():#当成绩名字相等,按年龄排序

if students[j].getAge()>students[j+1].getAge():

students[j],students[j+1]=students[j+1],students[j]

for i in students: #输出

print(i.getName(),i.getAge(),i.getGrade(),sep=' ')

from search import search_by_id

stat_submenu = '''
    5 统计 ---|---  1 学生总分   
              |---  2 单科总成绩、平均分
              |---  3 单科最高分
              |---  4 总成绩排序
              |---  0 返回
'''


def scores_sum(db, sid):
    sum = 0
    if search_by_id(db, sid) == {}:
        print('  - %s does not exist.' % sid)
        sum = -1
    else:
        for i in db:
            if i['studentID'] == sid:
                sum = i['score_1'] + i['score_2'] + i['score_3']
    return sum


def object_sum(db, object_n):
    avg = 0
    sum = 0
    total = len(db)
    for i in db:
        sum += float(i[object_n])
    avg = sum / total
    return sum, avg


def object_max(db, object_n):
    max = 0
    for i in db:
        temp = float(i[object_n])
        if temp > max:
            max = temp
    return max

def object_sort(db):
    sum_list = []
    for i in db:
        sum = i['score_1'] + i['score_2'] + i['score_3']
        sum_list.append(sum)
    return sorted(sum_list)

def db_stat(db):
    temp_db = db
    while True:
        print(stat_submenu)
        option = input('  > Enter your option:')
        if option == '0':
            break
        elif option == '1':
            sid = input('  >> Student ID:')
            sum = scores_sum(db, sid.strip())
            if sum != -1:
                print('  - Sum_Score of %s is %f' % (sid, sum))
            continue
        elif option == '2':
            object_name = input('  > Object name:')
            sum, avg = object_sum(db, object_name.strip())
            print('  - Sum of the object %s is %f' % (object_name, sum))
            print('  - Average of the object %s is %f' % (object_name, avg))
            continue
        elif option == '3':
            object_name = input('  > Object name:')
            max = object_max(db, object_name.strip())
            print('  - The maximum of the object %s is %f' % (object_name, max))
            continue
        elif option == '4':
            object_name = input('  > Object name:')
            sort = object_sort(db)
            print('  - The sort object %s is %s' % (object_name, str(sort)))
            continue
        else:
            print('  - Inputting WRONG!')
            continue


if __name__ == '__main__':
    db_stat([])
    pass