题解 | #成绩排序#python

成绩排序

https://www.nowcoder.com/practice/0383714a1bb749499050d2e0610418b1

import functools
# 升序 小到大
def ascend(a, b):
    if a[1] > b[1]:
        return 1
    elif a[1] < b[1]:
        return -1
    else:
        return 0
# 降序 大到小
def descent(a, b):
    if a[1] > b[1]:
        return -1
    elif a[1] < b[1]:
        return 1
    else:
        return 0

while True:
    try:
        n = int(input())
        mode = int(input())
        alist = []
        while n:
            user, grade = input().split()
            alist.append((user, int(grade)))
            n -= 1
            # 降序 大到小
        if mode == 0:
            alist.sort(key=functools.cmp_to_key(descent))
            # 升序 小到大
        elif mode == 1:
            alist.sort(key=functools.cmp_to_key(ascend))
        else:
            print("输入的排序方法有误")
        for item in alist:
            print(item[0], item[1])
    except:
        break

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务