Python 中的嵌套 for 循环
我想做类似的事情
for a in [0..1]:
for b in [0..1]:
for c in [0..1]:
do something
,但是,我可能有 15 个不同的变量。有没有更简单的方法,例如
for a, b, c in [0..1]:
do something
感谢您的帮助
I want to do something like
for a in [0..1]:
for b in [0..1]:
for c in [0..1]:
do something
But, I might have 15 different variables. Is there a simpler way like
for a, b, c in [0..1]:
do something
Thanks for any help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
itertools.product
:itertools.product
:您可以迭代所有这些的乘积。使用 itertools.product 并传递您的范围。
产量
You can iterate over the product of all of them. Use itertools.product and pass in your ranges.
yields
听起来你有一个需要处理的变量矩阵/列表。因此,最好的(也是最快的)解决方案是使用矩阵/列表工具。
如:Python
itertools
包。正如其他人所暗示的那样,itertools.product可能就是您想要的。但是,请参阅以下位置的完整列表:
http://docs.python.org/library/itertools.html
祝你好运。
It sounds like you have a matrix/list of variables you need to process. Thus, the best (and speediest) solution is to use a matrix/list tool.
Such as: The Python
itertools
package.As other have hinted,
itertools.product
is probably what you want. But, see the full list at:http://docs.python.org/library/itertools.html
Good luck.