如何在Python中制作n维嵌套的for循环? [英] How to make n-dimensional nested for-loops in Python?

查看:146
本文介绍了如何在Python中制作n维嵌套的for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

for x1 in range(x1, x2):
    for x2 in range(x3, x4):
        for x3 ...
            ...
                f(x1, x2, x3, ...)

如何将其转换为仅告诉python创建 n 嵌套循环的机制,其中变量名称为x1,x2 ,x3,x4,...?我当然不想手动写所有可能性,因为可能有很多尺寸。

How to convert this to a mechanism in which I only tell python to make n nested loops where the variable name is x1, x2, x3, x4, ...? I don't want to write every possibility manually of course, since there might be very many dimensions.

推荐答案

您想要的要做的就是迭代一个产品。使用 itertools.product

What you want to do is iterate over a product. Use itertools.product.

import itertools

ranges = [range(x1, x2), range(x3, x4), ...]

for xs in itertools.product(*ranges):
    f(*xs)



示例



Example

import itertools

ranges = [range(0, 2), range(1, 3), range(2, 4)]

for xs in itertools.product(*ranges):
    print(*xs)



输出



Output

0 1 2
0 1 3
0 2 2
0 2 3
1 1 2
1 1 3
1 2 2
1 2 3

这篇关于如何在Python中制作n维嵌套的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆