双重嵌套for循环的Pythonic快捷方式? [英] Pythonic shortcut for doubly nested for loops?

查看:88
本文介绍了双重嵌套for循环的Pythonic快捷方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下,如果我有一个接受元组参数(x,y)的函数,其中x在range(X)内,而y在range(Y)内,则通常的做法是:

Consider if I had a function that took a tuple argument (x,y), where x was in the range(X), and y in the range(Y), the normal way of doing it would be:

for x in range(X):
    for y in range(Y):
        function(x,y)

有办法吗

for xy in something_like_range(X,Y):
    function(xy)

以至于xy是一个元组(x,y)?

such that xy was a tuple (x,y)?

推荐答案

您可以使用 itertools产品

>>> from itertools import product
>>> 
>>> for x,y in product(range(3), range(4)):
...   print (x,y)
... 
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(1, 0)
(1, 1)
(1, 2)
(1, 3)

... and so on

您的代码如下:

for x,y in product(range(X), range(Y)):
    function(x,y)

这篇关于双重嵌套for循环的Pythonic快捷方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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