Nested for loops in Python

后端 未结 3 895
灰色年华
灰色年华 2021-01-05 10:32

I want to do something like

for a in [0..1]:
    for b in [0..1]:
        for c in [0..1]:
            do something

But, I might have 15 di

3条回答
  •  青春惊慌失措
    2021-01-05 11:24

    You can iterate over the product of all of them. Use itertools.product and pass in your ranges.

    import itertools
    for i in itertools.product(range(2), range(3), range(2)):
    print (i)
    

    yields

    (0, 0, 0)
    (0, 0, 1)
    (0, 1, 0)
    (0, 1, 1)
    (0, 2, 0)
    (0, 2, 1)
    (1, 0, 0)
    (1, 0, 1)
    (1, 1, 0)
    (1, 1, 1) 
    (1, 2, 0)
    (1, 2, 1)
    

提交回复
热议问题