how to define dynamic nested loop python function

前端 未结 1 871
情书的邮戳
情书的邮戳 2020-12-16 17:49
a = [1]
b = [2,3]
c = [4,5,6]

d = [a,b,c]


for x0 in d[0]:
    for x1 in d[1]:
        for x2 in d[2]:
            print(x0,x1,x2)

Result:

<
相关标签:
1条回答
  • 2020-12-16 18:18

    You can use itertools to calculate the products for you and can use the * operator to convert your list into arguments for the itertools.product() function.

    import itertools
    
    a = [1]
    b = [2,3]
    c = [4,5,6]
    
    args = [a,b,c]
    
    for combination in itertools.product(*args):
        print combination
    

    Output is

    (1, 2, 4)
    (1, 2, 5)
    (1, 2, 6)
    (1, 3, 4)
    (1, 3, 5)
    (1, 3, 6)
    
    0 讨论(0)
提交回复
热议问题