Python中如何避免字典和元組的多重巢狀的方法

小小程序员ol發表於2024-05-14

一、字典、元組的多重巢狀

例 1:記錄全班學生的成績。

分析:定義一個 SimpleGradebook類,

學生名是字典self._grades的鍵,成績是字典self._grades的值。

class SimpleGradebook():
    def __init__(self):
        self._grades = {}
    def add_student(self, name):
        self._grades[name] = []
    def report_grade(self, name, score):
        self._grades[name].append(score)
    def average_grade(self, name):
        grades = self._grades[name]
        return self._grades, sum(grades) / len(grades)
book = SimpleGradebook()
book.add_student('qinlu')
book.report_grade('qinlu', 99)
print(book.average_grade('qinlu'))
({'qinlu': [99]}, 99.0)

字典可能因為功能過多導致結果多重巢狀。

例 2:擴充 SimpleGradebook類,按科目儲存成績。

分析:定義一個 BySubjectGradebook類,字典by_subject巢狀在字典self._grades內。

學生名是字典self._grades的鍵,科目、成績是self._grades的值。

科目是字典by_subject的鍵,成績是字典by_subject的值。

class BySubjectGradebook():
    """
        report_grade(), average_grade()巢狀了兩層的字典
    """
    def __init__(self):
        self._grades = {}
    def add_student(self, name):
        self._grades[name] = {}
    def report_grade(self, name, subject, score):
        by_subject = self._grades[name]
        grade_list = by_subject.setdefault(subject, [])
        grade_list.append(score)
    def average_grade(self, name):
        by_subject = self._grades[name]
        total, count = 0, 0
        for scores in by_subject.values():
            total += sum(scores)
            count += len(scores)
        return self._grades, total / count
book = BySubjectGradebook()
book.add_student('qinlu')
book.report_grade('qinlu', 'Math', 99)
book.report_grade('qinlu', 'Math', 88)
book.report_grade('qinlu', 'Computer', 90)
book.report_grade('qinlu', 'Computer', 80)
print(book.average_grade('qinlu'))
({'qinlu': {'Math': [99, 88], 'Computer': [90, 80]}}, 89.25)

例 3:需求變更,需記錄每次成績佔總成績的權重。(期中、期末考試所佔的分量比隨堂考大)

class WeightedGradebook():
    def __init__(self):
        self._grades = {}
    def add_student(self, name):
        self._grades[name] = {}
    def report_grade(self, name, subject, score, weight):
        by_subject = self._grades[name]
        grade_list = by_subject.setdefault(subject, [])
        grade_list.append(score, weight)
    def average_grade(self, name):
        by_subject = self._grades[name]
        score_sum, score_count = 0, 0
        for subject, scores in by_subject.items():
            subject_avg, total_weight = 0, 0
            for score, weight in scores:
                #...
        return score_sum / score_count
book = WeightedGradebook()
book.add_student('qinlu')
book.report_grade('qinlu', 'Math', 99, 0.1)
book.report_grade('qinlu', 'Math', 88, 0.6)
book.report_grade('qinlu', 'Computer', 90, 0.1)
book.report_grade('qinlu', 'Computer', 80, 0.6)
print(book.average_grade('qinlu'))

該程式碼出現字典、元組的多層巢狀,應拆解為類。多層巢狀的程式碼,很難維護。

二、巢狀結構重構為類

將下面的字典重構為類。

字典by_subject巢狀在字典self._students內。

{'qinlu': {'Math': [(99, 0.1), (88, 0.9)], 'Computer': [(90. 0.1), (80, 0.9)]}}

分析:

  • Gradebook()類,學生名是字典self._students的鍵;科目、成績、權重是self._grades的值。

  • Student()類,科目是字典self._subjects的鍵;成績、權重是self._subjects的值。

  • Subject()類,成績是列表self._grades的第一位;權重是列表self._grades的第二位。

從最底層開始重構,即考試成績。這麼簡單的資訊,沒必要寫成類。

namedtuple()命名元組。

from collections import namedtuple
#學習中遇到問題沒人解答?小編建立了一個Python學習交流群:153708845

Grade = namedtuple('Grade', ('score', 'weight'))

# 科目類,該類包含考試成績
class Subject():
    def __init__(self):
        self._grades = []
    def report_grade(self, score, weight):
        self._grades.append(Grade(score, weight))
    def average_grade(self):
        total, total_weight = 0, 0
        # print(self._grades)
        for grade in self._grades:
            # print(grade)
            total += grade.score * grade.weight
            total_weight += grade.weight
        return total / total_weight

# 學生類,該類包含學習課程
class Student():
    def __init__(self):
        self._subjects = {}
    def subject(self, name):
        if name not in self._subjects:
            self._subjects[name] = Subject()
        return self._subjects[name]
    def average_grade(self):
        total, count = 0, 0
        for subject in self._subjects.values():
            total += subject.average_grade()
            count += 1
        return total / count

# 成績冊類,包含所有學生考試成績的容器類,該容器類以學生名字為鍵,可動態新增學生
class Gradebook():
    def __init__(self):
        self._students = {}
    def student(self, name):
        if name not in self._students:
            self._students[name] = Student()
        return self._students[name]

book = Gradebook()
qin = book.student('qinlu')
math = qin.subject('Math')
math.report_grade(99, 0.1)
math.report_grade(88, 0.9)
print(qin.average_grade())
89.1

雖然程式碼量是原來的兩倍,但更清晰,更易擴充套件,理解起來比原來容易。

相關文章