Python:动态嵌套的for循环,每个循环具有不同的范围 [英] Python: Dynamic nested for loops each with different range

查看:504
本文介绍了Python:动态嵌套的for循环,每个循环具有不同的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个代码,该代码可以迭代一个动态数(N)的嵌套循环,每个循环的范围都不同. 例如:

I want to create a code that can iterate over a dynamic number (N) of nested loops each with different range. For example:

N=3 
ranges=[[-3, -2, -1, 0, 1, 2, 3],
 [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
  [-3, -2, -1, 0, 1, 2, 3]]

for x in ranges[0]:
    for y in ranges[1]:
        for z in range[2]:
            variable=[x, y, z]

我是python的新手.当我浏览这里发布的类似问题时,我了解可以使用递归或itertools完成.但是,在每个级别的不同范围内,没有发布的答案可以解决此问题. 与我的最接近的发布问题是可嵌套的for循环数量范围固定.但是,user633183发布的答案在python 3.X中编码,而我在python 2.7中编码,因此我无法实现它,因为其某些代码在python 2.7上不起作用. 您能帮我编码这个问题吗?谢谢!

Im new to python. As I went over similar questions posted here I have the understanding that this can be done with recursion or itertools. However, none of the answers posted solve this problem for a different range at each level. The closest posted question similar to mine was Variable number of nested for loops with fixed range . However, the answer posted by user633183 is coded in python 3.X and I am coding in python 2.7 so I couldn't implement it as some of its code does not work on python 2.7. Can you please help me to code this problem. Thanks!

推荐答案

您的代码等效于itertools.product:

print(list(itertools.product(*ranges)))

这篇关于Python:动态嵌套的for循环,每个循环具有不同的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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