首页 > 其他分享 > 循环嵌套问题的解决方案

循环嵌套问题的解决方案

时间:2022-12-21 09:24:15浏览次数:28  
标签:product 解决方案 list 嵌套 嵌套循环 循环 70

# 循环嵌套问题的解决

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

    幸运的是,在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)

标签:product,解决方案,list,嵌套,嵌套循环,循环,70
From: https://www.cnblogs.com/yangzilaing/p/16995503.html

相关文章