Pythonic shortcut for doubly nested for loops?

前端 未结 5 795
再見小時候
再見小時候 2021-02-12 16:28

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          


        
5条回答
  •  终归单人心
    2021-02-12 17:17

    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)
    

提交回复
热议问题