Pythonic shortcut for doubly nested for loops?

前端 未结 5 794
再見小時候
再見小時候 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:04

    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
    

提交回复
热议问题