用于循环的双重嵌套的Pythonic快捷方式?

时间:2011-03-28 16:25:17

标签: python for-loop tuples nested-loops

考虑我是否有一个带有元组参数(x,y)的函数,其中x在范围(X)中,y在范围(Y)中,正常的方法是:

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)?

5 个答案:

答案 0 :(得分:16)

您可以使用product from 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)

答案 1 :(得分:5)

您可以使用itertools.product()

from itertools import product
for xy in product(range(X), range(Y)):
    function(xy)

答案 2 :(得分:4)

Pythonic他们是 - > (根据您的要求修改

>>> [ (x,y)   for x in range(2)   for y in range(2)]
[(0, 0), (0, 1), (1, 0), (1, 1)]

生成器版本

gen = ( (x,y)   for x in range(2)   for y in range(2) )
>>> for x,y in gen:
...     print x,y
... 
0 0
0 1
1 0
1 1

答案 3 :(得分:2)

尝试使用itertools产品:http://docs.python.org/library/itertools.html#itertools.product

from itertools import product

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

答案 4 :(得分:0)

from itertools import product

def something_like_range(*sizes):
    return product(*[range(size) for size in sizes])

用于接近您想要的用法:

for x,y in something_like_range(X,Y):
    your_function(x,y)

=)