views:

93

answers:

2

I have a map, let's call it M, which contains data mapped through N dimensions.

# If it was a 2d map, I could iterate it thusly:
start, size = (10, 10), (3, 3)
for x in range(start[0], start[0]+size[0]):
    for y in range(start[1], start[1]+size[1]):
        M.get((x, y))
# A 3d map would add a for z in ... and access it thusly
M.get((x, y, z)
# And so on.

My question is: How do I make an iterator that can yield the correct iteration sequence? That is, given start, size = (10, 10), (3, 3) it would yield the 2-tuple sequence (10, 10), (10, 11), (10, 12), (11, 10), (11, 11) etc. And given start, size = (10, 10, 10), (3, 3, 3) it would yield the correct 3-tuple sequence.

Yeah, I tried myself, but my head exploded. Or I can't justify spending time figuring it out, even though it's fun. Take your pick :)

+7  A: 

In Python 2.6+:

itertools.product(*[xrange(i, i+j) for i,j in zip(start, size)])
llasram
A: 

With do it your self generator expreessions:

start, size = (10, 10), (3, 3)
values2=((x+xd,y+yd)
        for x,y in (start,)
        for xr,yr in (size,)
        for xd in range(xr)
        for yd in range(yr))

for x,y in values2:
    print x,y

start, size = (10, 10, 10), (3, 3, 3)
values3=((x+xd,y+yd, z+zd)
        for x,y,z in (start,)
        for xr,yr,zr in (size,)
        for xd in range(xr)
        for yd in range(yr)
        for zd in range(zr))

for x,y,z in values3:
    print x,y,z
Tony Veijalainen