Automatically nested for loops in python
I am aware that two collections can be accessed simultaneously using
for i,j in zip([1,2,3],[4,5,6]):
print i,j
1 4
2 5
3 6
What I would like to do is something like this:
for i,j in [[1,2,3],[4,5,6]]:
print i,j
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
I want python to automatically create the ne开发者_如何学JAVAsted for loop for me. I would like to avoid using many nested for loops in my code when the list dimension gets up to 5 or 6. Is this possible?
Try
for i, j in itertools.product([1, 2, 3], [4, 5, 6]):
print i, j
>>> [[x,y] for x in [1,2,3] for y in [4,5,6]]
[[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6]]
It should be pretty easy to get what you want out of the resulting list.
I've had some cases where the logic for what needs to be iterated over is rather complex -- so you can always break that piece out into it's own generator:
def it():
i = 0
for r in xrange(rows):
for c in xrange(cols):
if i >= len(images):
return
yield r, c, images[i], contents[i]
i += 1
for r, c, image, content in it():
# do something...
But typically I find just spelling simple nested loops out to be better than obfuscating what you're looping over into a call to some other code. If you have more than 2-3 loops nested, the code probably needs refactoring anyway.
精彩评论