简体   繁体   English

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

[英]Alternative to nested for loops in Python3

I have a piece of code that compares a student's skill level to an assignment's difficulty level.我有一段代码可以将学生的技能水平与作业的难度水平进行比较。 It tries to match the student's level to the highest possible assignment difficulty.它试图将学生的水平与可能的最高作业难度相匹配。 I have achieved success using two nested for loops.我使用两个嵌套的 for 循环取得了成功。 However, it is incredibly inefficient when the number of values increases.然而,当值的数量增加时,它的效率非常低。

    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)

I have also looked into using itertools.product but I'm unsure on how to compare the two variables in the Cartesian product.我也研究过使用itertools.product但我不确定如何比较笛卡尔积中的两个变量。 results = list(product(student, difficulty)) produces (1,1) (1,2) (1,3) (2,1)... and so on. results = list(product(student, difficulty))产生(1,1)(1,2)(1,3)(2,1)......等等。 Is there any way to compare the values in the pair?有没有办法比较这对中的值?

You write: "However, it is incredibly inefficient when the number of values increases."你写道:“但是,当值的数量增加时,它的效率非常低。” Why?为什么? The more data, the more time it takes to process it.数据越多,处理它所需的时间就越多。 I don't think nested loops are an “incredible” issue for the performance of your function.我不认为嵌套循环对于您的函数性能来说是一个“令人难以置信”的问题。 Performance can be increased by using the most appropriate data structures and their processing algorithms.可以通过使用最合适的数据结构及其处理算法来提高性能。

As for your function, it can be rewritten in a more readable form:至于你的函数,它可以改写成更易读的形式:

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

PS聚苯乙烯

Firstly, it's a bad idea to use a global variable inside a function and change it at the same time.首先,在函数内部使用global变量并同时更改它是一个坏主意。 What prevents you from declaring a local variable?是什么阻止您声明局部变量?

Secondly, when declaring a function, you wrote that it returns an int value, but in fact it returns a str .其次,在声明一个函数时,你写道它返回一个int值,但实际上它返回一个str

Thirdly, using an exception to get out of a loop seems very strange.第三,使用异常跳出循环似乎很奇怪。

I dont think more loops are bad here, but efficient Data-Structures will come in handy.我不认为更多的循环在这里不好,但高效的数据结构会派上用场。 You can keep ranges of difficulty in a dictionary - in the format:您可以在字典中保留难度范围 - 格式如下:

scores = dict(zip(difficulty, points))

Now I feel its more organized than before.现在我觉得它比以前更有条理。

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)

Let me know if this helps.如果这有帮助,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM