python中自动嵌套for循环

发布于 2024-10-13 09:16:55 字数 314 浏览 5 评论 0原文

我知道可以使用同时访问两个集合

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北城孤痞 2024-10-20 09:16:55

尝试

for i, j in itertools.product([1, 2, 3], [4, 5, 6]):
    print i, j

Try

for i, j in itertools.product([1, 2, 3], [4, 5, 6]):
    print i, j
鲜肉鲜肉永远不皱 2024-10-20 09:16:55
>>> [[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]]

从结果列表中获取您想要的内容应该很容易。

>>> [[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.

独守阴晴ぅ圆缺 2024-10-20 09:16:55

我遇到过一些情况,需要迭代的逻辑相当复杂——所以你总是可以将该部分分解成它自己的生成器:

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...

但通常我发现仅仅拼写简单的嵌套循环比混淆什么要好您正在循环调用其他一些代码。如果嵌套的循环超过 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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文