python中自动嵌套for循环
我知道可以使用同时访问两个集合
for i,j in zip([1,2,3],[4,5,6]):
print i,j
1 4
2 5
3 6
我想做的是这样的:
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
我希望 python 自动为我创建嵌套的 for 循环。当列表维度达到 5 或 6 时,我想避免在代码中使用许多嵌套的 for 循环。这可能吗?
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 nested 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试
Try
从结果列表中获取您想要的内容应该很容易。
It should be pretty easy to get what you want out of the resulting list.
我遇到过一些情况,需要迭代的逻辑相当复杂——所以你总是可以将该部分分解成它自己的生成器:
但通常我发现仅仅拼写简单的嵌套循环比混淆什么要好您正在循环调用其他一些代码。如果嵌套的循环超过 2-3 个,则代码可能无论如何都需要重构。
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:
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.