簡體   English   中英

Python3 中嵌套 for 循環的替代方法

[英]Alternative to nested for loops in Python3

我有一段代碼可以將學生的技能水平與作業的難度水平進行比較。 它試圖將學生的水平與可能的最高作業難度相匹配。 我使用兩個嵌套的 for 循環取得了成功。 然而,當值的數量增加時,它的效率非常低。

    def maxAssignmentPoints(self, difficulty, points, student) -> int:
        global totalPoints
        totalPoints = 0
        for i in range(len(student)):
            for j in range(len(difficulty)):
                if student[i] > difficulty[j]:
                    try:
                        if student[i] < difficulty[j + 1]:
                            totalPoints += points[j]
                    except IndexError:
                        break
                if student[i] == difficulty[j]:
                    totalPoints += points[j]
        return str(totalPoints)

我也研究過使用itertools.product但我不確定如何比較笛卡爾積中的兩個變量。 results = list(product(student, difficulty))產生(1,1)(1,2)(1,3)(2,1)......等等。 有沒有辦法比較這對中的值?

你寫道:“但是,當值的數量增加時,它的效率非常低。” 為什么? 數據越多,處理它所需的時間就越多。 我不認為嵌套循環對於您的函數性能來說是一個“令人難以置信”的問題。 可以通過使用最合適的數據結構及其處理算法來提高性能。

至於你的函數,它可以改寫成更易讀的形式:

def max_assignment_points(difficulties: list, points: list, students: list) -> int:
    total_points = 0
    for student in students:
        for i in range(len(difficulties) - 1):
            if difficulties[i] < student < difficulties[i + 1]:
                total_points += points[i]
            elif student == difficulties[i]:
                total_points += points[i]
    return total_points

聚苯乙烯

首先,在函數內部使用global變量並同時更改它是一個壞主意。 是什么阻止您聲明局部變量?

其次,在聲明一個函數時,你寫道它返回一個int值,但實際上它返回一個str

第三,使用異常跳出循環似乎很奇怪。

我不認為更多的循環在這里不好,但高效的數據結構會派上用場。 您可以在字典中保留難度范圍 - 格式如下:

scores = dict(zip(difficulty, points))

現在我覺得它比以前更有條理。

def maxAssignmentPoints(self, students, scores) -> int:
    totalPoints = 0
    for student in range(students):
        if scores.get(student, None) is not None:
            total_points += scores[student]
    return str(totalPoints)

如果這有幫助,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM