问题
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]
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!
回答1:
Your code is equivalent to itertools.product
:
print(list(itertools.product(*ranges)))
回答2:
So, if I am understanding your question correctly, you want the values being iterated over to be [-3, -5, -3], [-2, -4, -2]...
. This can be accomplished easily with zip function built into python:
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. Using this *
splat notation avoids even having to know about the number of lists being combined.
来源:https://stackoverflow.com/questions/50636404/python-dynamic-nested-for-loops-each-with-different-range