Is there a Python equivalent of range(n) for multidimensional ranges?

前端 未结 7 903
囚心锁ツ
囚心锁ツ 2020-12-08 09:19

On Python, range(3) will return [0,1,2]. Is there an equivalent for multidimensional ranges?

range((3,2)) # [(0,0),(0,1),(1,0),(1,1),(2,0),(2,1)]
         


        
7条回答
  •  生来不讨喜
    2020-12-08 09:55

    There actually is a simple syntax for this. You just need to have two fors:

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

提交回复
热议问题