Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

So, for example, looping though the tiles of a rectangular area on a tile-based game could be written as:

for x,y in range((3,2)): 

Note I'm not asking for an implementation. I would like to know if this is a recognized pattern and if there is a built-in function on Python or it's standard/common libraries.

like image 476
MaiaVictor Avatar asked Apr 10 '12 17:04

MaiaVictor


2 Answers

You could use itertools.product():

>>> import itertools >>> for (i,j,k) in itertools.product(xrange(3),xrange(3),xrange(3)): ...     print i,j,k 

The multiple repeated xrange() statements could be expressed like so, if you want to scale this up to a ten-dimensional loop or something similarly ridiculous:

>>> for combination in itertools.product( xrange(3), repeat=10 ): ...     print combination 

Which loops over ten variables, varying from (0,0,0,0,0,0,0,0,0,0) to (2,2,2,2,2,2,2,2,2,2).


In general itertools is an insanely awesome module. In the same way regexps are vastly more expressive than "plain" string methods, itertools is a very elegant way of expressing complex loops. You owe it to yourself to read the itertools module documentation. It will make your life more fun.

like image 24
Li-aung Yip Avatar answered Sep 20 '22 04:09

Li-aung Yip


In numpy, it's numpy.ndindex. Also have a look at numpy.ndenumerate.

E.g.

import numpy as np for x, y in np.ndindex((3,2)):     print(x, y) 

This yields:

0 0 0 1 1 0 1 1 2 0 2 1 
like image 116
Joe Kington Avatar answered Sep 24 '22 04:09

Joe Kington