In python is there an easier way to write 6 nested for loops?

后端 未结 11 1560
长情又很酷
长情又很酷 2020-12-04 17:49

This problem has been getting at me for a while now. Is there an easier way to write nested for loops in python? For example if my code went something like this

11条回答
  •  渐次进展
    2020-12-04 18:29

    If you're frequently iterating over a Cartesian product like in your example, you might want to investigate Python 2.6's itertools.product -- or write your own if you're in an earlier Python.

    from itertools import product
    for y, x in product(range(3), repeat=2):
      do_something()
      for y1, x1 in product(range(3), repeat=2):
        do_something_else()
    

提交回复
热议问题