简体   繁体   English

Python:动态嵌套for循环,每个循环具有不同的范围

[英]Python: Dynamic nested for loops each with different range

I want to create a code that can iterate over a dynamic number (N) of nested loops each with different range. 我想创建一个代码,该代码可以遍历每个具有不同范围的动态数量(N)的嵌套循环。 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]

Im new to python. 我是python的新手。 As I went over similar questions posted here I have the understanding that this can be done with recursion or itertools. 当我浏览这里发布的类似问题时,我了解可以使用递归或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. 但是,user633183发布的答案在python 3.x中编码,而我在python 2.7中编码,因此我无法实现它,因为其某些代码在python 2.7上不起作用。 Can you please help me to code this problem. 您能帮我编码这个问题吗? Thanks! 谢谢!

您的代码等效于itertools.product

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

So, if I am understanding your question correctly, you want the values being iterated over to be [-3, -5, -3], [-2, -4, -2]... . 因此,如果我正确地理解了您的问题,则希望迭代的值为[-3, -5, -3], [-2, -4, -2]... This can be accomplished easily with zip function built into python: 这可以通过python内置的zip函数轻松实现:

for x in zip(*ranges):
    # Do something with x

x will take on a tuple of all the first values, then a tuple of all the second values, etc, stopping when the shortest list ends. x将采用所有第一个值的元组,然后是所有第二个值的元组,以此类推,直到最短列表结束时停止。 Using this * splat notation avoids even having to know about the number of lists being combined. 使用此* splat表示法,甚至不必知道要组合的列表数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM