【问题标题】:is there way to reduce n times nested for-loop in python [duplicate]有没有办法减少python中嵌套for循环的n次[重复]
【发布时间】:2021-08-27 06:51:31
【问题描述】:

我有 7 个迭代参数:list_1 到 list_7 下面的代码是静态的,使用 7 个 for 循环,但我有动态 n 迭代参数,需要使用 n for-loop

for a in list_1:
    for b in list_2:
        for c in list_3:
            for d in list_4:
                for e in list_5:
                    for f in list_6:
                        for g in list_7:
                            print(a,b,c,d,e,f,g)

是否有任何简单的解决方案可以使用 pandas 或 python list 或 numpy 来解决这个问题 注意:所有列表都包含字符串值

【问题讨论】:

    标签: python for-loop


    【解决方案1】:

    使用itertools.product

    import itertools
    all_lists = [list_1, list_2, list_3, list_4, list_5, list_6, list_7]
    product = list(itertools.product(all_lists))
    

    打印示例:

    for i in itertools.product(['a', 'b', 'c'], ['1', '2', '3']):
        print(*i)
    

    输出:

    a 1
    a 2
    a 3
    b 1
    b 2
    ...
    

    【讨论】:

      猜你喜欢
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 2023-03-27
      • 2010-09-30
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多