Python 避免字典和元組的多重嵌套問題

一、字典、元組的多重嵌套

例 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

該代碼出現字典、元組的多層嵌套,應拆解為類。多層嵌套的代碼,很難維護。

二、嵌套結構重構為類

將下面的字典重構為類。

字典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()命名元組。

'''
學習中遇到問題沒人解答?小編創建瞭一個Python學習交流群:711312441
尋找有志同道合的小夥伴,互幫互助,群裡還有不錯的視頻學習教程和PDF電子書!
'''
from collections import namedtuple

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

雖然代碼量是原來的兩倍,但更清晰,更易擴展,理解起來比原來容易。

到此這篇關於Python 避免字典和元組的多重嵌套的文章就介紹到這瞭,更多相關Python 多重嵌套內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: