Loading

Python--MutableDict使用范例

MutableDict 使用dict的抽象基类MutableDict,创建自定义dict

from abc import ABC
from enum import Enum
from collections import defaultdict
from collections import MutableMapping


# 统计班级每个成绩等级的人数
class GradeLevel(str, Enum):
    EXCELLENT = 'gte 95'
    GOOD = 'gte 85 and lt 95'
    NORMAL = 'gte 70 lt 85'
    PASS = 'gte 60 and lt 70'
    FAIL = 'lt 60'


class GradeLevelDict(MutableMapping, ABC):
    def __init__(self):
        self.data = defaultdict(int)

    def __getitem__(self, key):
        return self.data[self.grade_level(key)]

    def __setitem__(self, key, value):
        self.data[self.grade_level(key)] = value

    def __delitem__(self, key):
        del self.data[key]

    def __iter__(self):
        return iter(self.data)

    def __len__(self):
        return len(self.data)

    def items(self):
        return sorted(self.data.items(), key=lambda x: list(GradeLevel).index(x[0]))

    def student_count(self):
        return sum(self.data.values())

    @staticmethod
    def grade_level(score):
        if score in list(GradeLevel):
            return score
        if score >= 95:
            return GradeLevel.EXCELLENT
        if 85 <= score < 95:
            return GradeLevel.GOOD
        if 70 <= score < 85:
            return GradeLevel.NORMAL
        if 60 <= score < 70:
            return GradeLevel.PASS
        else:
            return GradeLevel.FAIL


if __name__ == '__main__':
    grade_lv_dic = GradeLevelDict()
    grade_lv_dic[99] += 1
    grade_lv_dic[55] += 1
    print()

posted @ 2022-04-19 21:37  MrSu  阅读(87)  评论(0编辑  收藏  举报