在python中有没有更简单的方法来编写6个嵌套的for循环? [英] In python is there an easier way to write 6 nested for loops?

查看:34
本文介绍了在python中有没有更简单的方法来编写6个嵌套的for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经困扰我一段时间了.有没有更简单的方法在 python 中编写嵌套的 for 循环?例如,如果我的代码是这样的:

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:

  for y in range(3):
    for x in range(3):
      do_something()
      for y1 in range(3):
        for x1 in range(3):
          do_something_else()

有没有更简单的方法来做到这一点?我知道这段代码有效,但是当你像我一样缩进而不是使用 2 个空格时,它可能会成为一个问题.

would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem.

哦,在这个例子中,只有 4 个嵌套的 for 循环让事情变得更容易.

Oh in the example there were only 4 nested for loops to make things easier.

推荐答案

如果您像示例中那样经常迭代笛卡尔积,您可能需要研究 Python 2.6 的 itertools.product -- 如果您使用的是较早的 Python,请自行编写.

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()

这篇关于在python中有没有更简单的方法来编写6个嵌套的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆