循环嵌套问题的解决方案

# 循环嵌套问题的解决

  • 当一个程序变得复杂时,你不可避免地要写嵌套循环。然而,嵌套循环将使程序更难阅读和维护。

    幸运的是,在Python中你总是可以通过内置的 product() 函数避免嵌套循环。

#如下面的我们需要嵌套循环
list_a = [1, 2020, 70]
list_b = [2, 4, 7, 2000]
list_c = [3, 70, 7]

for a in list_a:
    for b in list_b:
        for c in list_c:
            if a + b + c == 2077:
                print(a, b, c)


#可以从itertools对象中调用product对象来减少循环的嵌套                
from itertools import product

list_a = [1, 2020, 70]
list_b = [2, 4, 7, 2000]
list_c = [3, 70, 7]

for a,b,c in product(list_a,list_b,list_c):
    if a + b + c ==2077:
        print(a,b,c)
posted @ 2022-12-21 09:05  小杨的冥想课  阅读(85)  评论(2编辑  收藏  举报