Pythonic shortcut for doubly nested for loops?

半城伤御伤魂 提交于 2019-12-21 07:22:03

问题


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)

is there a way to do

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

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


回答1:


You can use 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

Your code would look like:

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



回答2:


You can use itertools.product():

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



回答3:


Pythonic they are -> (modify according to your requirements)

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

Generator version :

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



回答4:


Try product from 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)



回答5:


from itertools import product

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

for a usage close to what you wanted:

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

=)



来源:https://stackoverflow.com/questions/5462047/pythonic-shortcut-for-doubly-nested-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!